The reason for the title is simple: Kotlin hopes to make Android development simpler, more efficient, and more secure. Knowing that Kotlin is a short essay written from a simple book, I feel more and more that it is enough to share my learning and practice process and ideas in words, no matter how good the writing style is or how much the content is, if it can inspire others. So, thanks to the great god who wrote so many wonderful articles, and I’ve just started at the foot of the mountain.

Project source code on Github, interested friends can download, welcome to send stars and discussion. The dynamic renderings of Demo are as follows:

 

1. Kotlin’s environment configuration in Android Studio

Follow the instructions in the following two articles to complete the configuration of Kotlin’s environment in Android Studio (Eclipse does not recommend it) and learn the basic syntax and use cases. If you have any questions, you can refer to Baidu, Google or the Project and App build.gradle Settings in the shared Project source code. You can also leave a message for discussion.

Kotlinlang.org/docs/tutori…

Kotlinlang.org/docs/tutori…

In fact, similar to the introduction of ordinary plug-ins, to say the simple is to do two things:

A Install Kotlin plug-in;

B Add references to Porject and App build.gradle files;

If the configuration is ok, the option to convert Java Code to Kotlin Code appears at the bottom of the Code bar in the Studio toolbar:

If it is kt format, the option is grey and unclickable.

 

2. Summary of Kotlin learning and coding

Once the development environment is OK, as a beginner to Kotlin, there are two options:

A Directly create Android projects and Kotlin files, and tap Kotlin code from scratch while learning;

B open the previous Android project and convert one and several Java files into Kotlin code through the above conversion tool. By reading the converted code, you can quickly get familiar with the Kotlin code of the Android project.

It is recommended to start with the second method, which is relatively simple and generally has some minor errors or warnings after the Java code is transferred over, and also makes great progress during the modification process. Note: Kotlin isn’t just a replacement for Java on Android projects, it’s detailed on its website.

Here are a few of the things Kotlin has done to make code so clean, secure, and clever that the new language is maturing in ways that you can’t possibly cover in a single article or two. As we learn more, we will supplement it later.

2.1 the text & setText ()

1 text1.text = (Editable e)Copy the code

1 text1.setText(CharSequence text)Copy the code

Let’s start with a simple one. Text1 is the ID of the TextView component in a layout. That’s how you set the text. No TextView object declaration, no findViewById() call. There are some steps that Kotlin needs to take care of quietly, but as a developer, it’s definitely more efficient. The latter is commonly used because CharSequence or String are used more frequently. But Kotlin’s compact form tends to obj.field rather than setField(), except that converting CharSequence to Editable is a bit more cumbersome:

1 text1.text = Editable.Factory().newEditable(message)Copy the code

2.2 @ & when () {}

1 login_image_sel.setOnClickListener(this@LoginFragment)
2 login_in.setOnClickListener(this@LoginFragment)
3 login_reg.setOnClickListener(this@LoginFragment)
4 login_out.setOnClickListener(this@LoginFragment)Copy the code

Set clickListener for each of the four components with ids as view.onClickListener. If your class already inherits this and implements its onClick() method, write this as its own. The @name part, on the other hand, emphasizes the Name of the class (not written and does not affect compilation and execution), but is much more readable when written, so you can say that the @ part is written for the developer (or someone else who will read the code in the future).

 1 override fun onClick(view: View) {
 2     val id = view.id
 3     when (id) {
 4         R.id.login_image_sel -> selectImageBtn()
 5         R.id.login_in -> loginInBtn()
 6         R.id.login_reg -> loginRegBtn()
 7         R.id.login_out -> loginOutBtn()
 8         else ->{} 9     }
10 }Copy the code

The first line needs explaining. The Java code looks like this:

1 @Override
2 public void onClick(View view) {}Copy the code

There are several differences:

A @ Override – > Override.

B default->public, Kotlin default->public;

C void->: Unit, Kotlin;

1 override fun onClick(view: View): Unit {Copy the code

D View View -> View: View;

Kotlin liberated the Switch with when, and if you think about it, both the code form and the line count are much simpler. Having said goodbye to the original Java case, “:”, break, and default, I think the most immediate benefit is that once I enter when, I only execute the branch after the “->” corresponding to the match, and I don’t have to be careful where to add a break every time.

2.3 var & val

1 val id = view.idCopy the code

Following the topic above, let’s look at the definition of variables. The above code will be familiar to those familiar with scripting languages, so it sometimes feels like Kotlin is slowly combining the best of each language.

Val corresponds to var, where the former defines an impossible variable and the latter a variable that can be changed. In Kotlin, the burden of defining immutability is done by Val, and the variables they define must be assigned at declaration time (except for class direct attributes, more on that later).

So when we say a method parameter (view: view), we have a type view behind it. This is also true when we declare variables. Let’s look at a few examples:

1 var int1: Int = 1
2 var int2 = 2
3 var str3: String? = null
4 val str4: String? = nullCopy the code

Four variables are declared: two mutable ints, one mutable String, and one immutable String. Since immutable, the next assignment will be an error:

1 int1 = 2
2 int2 = 3
3 str3 = "Hello"
4Str4 = "Kotlin" // cursor: "Val cannot be reassigned"Copy the code

As you can see, Kotlin can no longer declare variables as Java does, such as:

1 var int3
2 var int4: IntCopy the code

Property must be initialized or be abstract.

The question mark after the type (String? = null), which indicates whether declared variables are allowed to be NULL. This is distinguished from the case where a variable is declared without being sure of its value, which can be resolved by assigning a value that does not affect the program. Such as:

1 var str3: String = "will be reassigned later"Copy the code

The “: String” qualifier can be omitted, and the compiler will automatically infer that there is no “?” .

So someone asks “?” What is the fundamental difference between nothing and nothing? It is the assignment to a variable during program execution. If null is assigned to the variable, the program raises an exception. It is usually used in function parameters. For example, the method parameters are defined as follows:

1 fun testNotNull(str: String) {}Copy the code

The value passed to the parameter STR on the call cannot be null, which is very useful. It is possible to determine whether the required parameters can be null in most application scenarios, such as the path to read images cannot be empty, the list cannot be empty when accessing elements through indexes, and so on. This is not to say that null-induced exceptions can be resolved perfectly, but that the point of exception can be brought forward, or that variables can be easily found and eliminated. As for how to use it in different scenarios, it needs further research, and not all NonNull is the best choice. Of course, non-null restrictions can also be implemented in Java code with the @nonNULL annotation.

“?” Another useful place is the method return value:

1 fun getStringLength(obj: Any): Int? {
2     if (obj is String)
3         return obj.length // no cast to String is needed
4     return null
5 }Copy the code

A null value declared as an int return value type in Java is not allowed and may return a token value if there is no desired result. Kotlin, on the other hand, simply checks to see if the return value is null, and if not, the return value is the desired result. The above code can also be abbreviated as:

1 fun getStringLength(obj: Any): Int? = if (obj is String) obj.length else nullCopy the code

If obj is not a String instance, return null. Java is instanceof.

2.4 Any

Any is a bit like Object in Java, the ancestor of objects. Go straight to the example:

1 fun showLog(message: Any?) {
2     Log.i(LOG_TAG, message?.toString())
3 }Copy the code

This is a custom log method in the Utils file. Message is of type Any? “, just to reinforce the concept of the previous one. For an argument passed in, it can be null or a variable value of any type; The key is the “? “after message. It determines whether message is null, returns the string “null” if so, and calls toString() if not. Note that this assumes that the argument object passed in inherits or overrides toString(), otherwise an error may occur.

2.5 Custom View

I’m not talking about the familiar custom circular View and using it in XML or Java, but rather generating the layout and components directly from the code, which is another of Kotlin’s strengths. Look at the code for customizing a Dialog:

 1 val dialog = Dialog(mContext, R.style.DialogNoTitle)
 2 dialog.setContentView(mContext.linearLayout {
 3     imageView {
 4         Utils.setImageToView(mContext, null, imageUri, this)
 5         onClick {
 6             dialog.dismiss()
 7         }
 8     }
 9 })
10 
11 dialog.show()Copy the code

The Style and Utils sections of the code can be viewed in the project source code, where the layout section is defined for Kotlin. To dynamically add a linearLayout and an image component, you only need to declare a single name, respectively linearLayout and imageView. The elements are bounded by {}. The imageView belongs to the linearLayout, while onClick {} and this belong to the imageView. The test found that the displayed Dialog is middle by default, and you can adjust it to achieve other effects.

2.6 Map

1 `object`.map {
2     var bulletinT = ReceiveBulletin(it.teacherName,
3             it.updatedAt,
4             it.bulletinContent,
5             it.bulletinImage?.fileUrl)
6     //do something
7 }Copy the code

Here 'object' can be either list data or some other collection type such as an array. The map simply iterates through each element in the collection, processing it in {}, and each element has a temporary name of "it". This means you don't have to see for or Iterator again.Copy the code

2.7 the Class

Variables mentioned in 2.3 val statement can first not the assignment, this kind of situation will appear in the Class declaration:

1 class BulletinAdapter(private val mContext: Context,
2                       private val mBulletins: ArrayList<ReceiveBulletin>)
3         : RecyclerView.Adapter<BulletinAdapter.ViewHolder>() {}Copy the code

Create a custom Adapter class to use in combination with RecyclerView. The class extends from Java to a colon “:”, as if entering the C++ world.

The class name is followed by a parenthesis “()” and has so many strange arguments that Kotlin explains it is equivalent to a quick constructor. The primary constructor method omits its name. The name “constructor” should not be omitted if the method has special modifications such as annotations before it. The method followed by the class is called primary because it is possible to implement secondary constructors in the class, so dig deeper later. Init is called only once when the class object is constructed, so it can be used as a marker for class instances, such as printing a log:

1 init {
2     Utils.showLog("Create a BulletinAdapter object")
3 }Copy the code

Val is not allowed to be changed in this class after an argument is passed to the parameter. But collections are a bit special, such as reassigning to mContext doesn’t work, but adding elements to mBulletins via the add() method does. There are concerns about the address the object points to and the elements it contains.

The purpose of the private access qualifier is similar to that in Java. It is not visible outside the class, that is, it does not allow variables to be accessed or changed outside the class.

2.8 if ()  {} else () {}

In 2.2, the when branch -> was followed by only one sentence. What if there were two? Let’s look at the if else case first:

1 if (position == itemCount - 1)
2     itemView.bulletin_divider.visibility = View.GONE
3 else
4     itemView.bulletin_divider.visibility = View.VISIBLECopy the code

When there are multiple statements in the branch, all code belonging to the branch must be included in {}, otherwise the else below will not match if, as in Java. Finally, Kotlin does not recommend ending a statement with a semicolon (;). “, it’s ok, just draw a gray reminder under the name of the variable.

 

3. Summary

3.1 Project introduction

At the beginning of the project source code download address and running dynamic renderings, now to a simple introduction. What you practice in the process of learning by yourself should not be called App, but rather Demo.

Demo has three pages: message receiving, message sending, and user information.

A Message reception: when the program is opened, the message will be read from the cloud database. If there is a message, it will be loaded; if there is no message, it will display a prompt (such as drop-down refresh later); A message includes the sender’s profile picture, name, sending time and message content (at least one of them is text or picture); If there is picture content, click and enlarge; Messages are received without user login requirements;

B Sending messages: Only registered and logged in users can send messages. Send at least one of the text or picture content;

C User information: Register first, do not set the existing user name in the database, must select the avatar, after successful generally automatic login; Log out only after login; You can log in again only after you log out.

The cloud database mentioned here refers to the free Bmob cloud platform used in the project, which is more suitable for personal practice. You can build tables and define information in tables by yourself.

3.2 Kotlin’s Future Learning Program

The points mentioned in this article and used in this project are just the tip of the Kotlin language iceberg. There are more interesting and wonderful places to discover. I believe that in the future, I can make the previously used and tedious code more concise and efficient implementation in the project.

Don’t let youth leave too many regrets, focus
Classification: Android, Kotlin
Tags: Kotlin, Android
Good writing is the best
Pay attention to my
Collect the paper

Footprints on the road



Attention – 3



Fans – 81.

+ add attention

7
0

The «The last:
Micro letter small program – train ticket inquiry



» Next up:
Android Material Design–TextInputLayout