Kotlin (2) makes App development easier. kotlinapp

Source: Internet
Author: User

Kotlin (2) makes App development easier. kotlinapp

The previous article introduced how to build the Kotlin development environment. However, this development environment is still based on Android Studio, and Java is used for coding on Android Studio, why should we create a special Kotlin? What are the advantages of this Kotlin over Java?

We can regard Kotlin as an upgraded Java version. It is not only fully compatible with Java, but also greatly simplifies the code syntax, so that developers can focus on coding business logic, there is no need to coordinate between tedious code frameworks. Of course, to make full use of the excellent features of Kotlin, in addition to importing the core library of Kotlin, you must also import the extension library and Anko library of Kotlin. To compile the configuration file, perform the following two modifications:
1. Open build. gradle of the project, add the anko version number statement, and the path of the Kotlin extension library. The complete compilation configuration is as follows:

buildscript {    ext.kotlin_version = "1.1.2"    ext.anko_version = "0.9"    repositories {        jcenter()    }    dependencies {        classpath 'com.android.tools.build:gradle:2.3.0'        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"    }}

2. Open build. gradle of the module, add the extension plug-in of Kotlin at the beginning of the file, and add the following Configuration:

apply plugin: 'kotlin-android'apply plugin: 'kotlin-android-extensions'

Then add the anko plugin compilation instructions under the dependencies node, as shown below:

    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"    compile "org.jetbrains.anko:anko-common:$anko_version"

After completing the compilation and Configuration modification, we will try to perform a simple Kotlin encoding to see how concise the Kotlin code is.

 

First, right-click the hello module package name, choose "New"> "Kotlin Activity" from the pop-up menu (you can also choose "File"> "New"> "Kotlin Activity" from the top menu). The right-click menu is as follows:

Select the menu, open the Activity creation page of Kotlin, and click "Next" to enter the creation Information page, as shown in:

Enter the Activity name EasyActivity. The layout file name is activity_easy. Click "Finish" to create EasyActivity. kt.

Now, add several TextView and Button controls to the layout file activity_easy.xml created earlier. The layout is relatively simple and will not be pasted. This article mainly introduces Kotlin development and does not detail the Java Development of Adnroid. Therefore, if you are not familiar with Android development, we recommend that you first follow the actual development practices of Android Studio: from scratch to App launch, I learned about basic Android development.

 

Next is the focus of this article. In the past, we had to obtain the control object through the findViewById method, and then call the relevant function to set the object property. For example, there is a TextView control named TV _hello, and you are going to change the displayed text of TV _hello to "hello" in the Code. The following two lines of code are used for Java encoding:

TextView TV _hello = (TextView) findViewById (R. id. TV _hello); TV _hello.setText ("hello ");

If you use Kotlin to modify the text function, what will happen? Next let's experiment. Add the following line at the beginning of EasyActivity. kt:

import kotlinx.android.synthetic.main.activity_easy.*

The purpose of this line of import statements is to introduce the automatic ing function of the control variables of Kotlin. The following code does not need to call the findViewById method and directly uses the Control ID as the control object. For example, to modify the display text of TextView, use the Kotlin encoding as long as one line is as follows:

TV _hello.setText ("hello ")

In this way, the original two lines of code are reduced to one line of code, removing the redundant code that originally obtained the control object. However, the convenience of Kotlin is not limited to this. It does not even need to call the set ***/get *** method for the control, but allows you to directly modify/obtain the property value of the control, for the text setting function, you can continue to simplify the following line of code:

TV _hello.text = "hello"

After further simplification, the "set" and two parentheses of the original code are removed, but the new Code is easier to understand.

 

Some people may say that Kotlin only streamlined a line of code here, but it does not necessarily have much advantage over Java, so we can continue to offer the primary keys for other common functions, with three victories in five games, winning more is enough to serve the public. The first game above is the PK for modifying the control text, and the result is Kotlin Xiaosheng. Next, we set up another four game PK, and the second game is the processing of the click listener. A Button is a commonly used Button control in Android. It is often used to process click events in the Code. The following Java code is an example of responding to a Button:

Final Button btn_click = (Button) findViewById (R. id. btn_click); btn_click.setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {btn_click.setText ("You clicked ");}});

In fact, this response function is very simple. You only need to modify the button text when you click the button. But because Java needs to click the listener, you have to write several lines of anonymous code. What if you use Kotlin to implement the same functions? See the following Kotlin code:

Btn_click.setOnClickListener {btn_click.text = "you clicked "}

Kotlin only needs a line of code to complete the process. If you don't think of it, Kotlin won the game.

 

In the third case, change the long-press event of the Button control. The following Java code is an example of responding to the long-press event of the Button:

Final Button btn_click_long = (Button) findViewById (R. id. btn_click_long); btn_click_long.setOnLongClickListener (new View. onLongClickListener () {@ Override public boolean onLongClick (View v) {btn_click_long.setText ("You have pressed for a while"); return true ;}});

We can see that the Java code is still lengthy. Let's take a look at how the Kotlin code works:

Btn_click_long.setOnLongClickListener {btn_click_long.text = "you have pressed for a short moment"; true}

Kotlin is still working with a line of code, which is really impressive. Kotlin is still winning.

 

In the fourth round, I am no better than the listener. Java suffers a lot in the anonymous class, so there is only one line of Java code for this function than another common Toast prompt function:

Final Button btn_toast = (Button) findViewById (R. id. btn_toast); btn_toast.setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {Toast. makeText (EasyJavaActivity. this, "Tips: You clicked", Toast. LENGTH_SHORT ). show ();}});

Ignore the click listener of the outer layer above. There is only one line of authentic Toast code, and you can see how to split Kotlin:

Btn_toast.setOnClickListener {toast ("Tip: You clicked ")}

Haha, Kotlin and listener code are less than Java's Toast code. In this case, Kotlin continues to win.

 

But why does the toast function of Kotlin differentiate the display duration? The default toast method is short-term display, that is, Toast. LENGTH_SHORT. The Java side is like this. Although my code is long, it is flexible enough. If I want to be short, I will be LENGTH_SHORT. If I want to be long, I will be LENGTH_LONG. The fifth round shows a long response to the Toast test. The Java code for this function also has only one line:

Final Button btn_toast_long = (Button) findViewById (R. id. btn_toast_long); btn_toast_long.setOnLongClickListener (new View. onLongClickListener () {@ Override public boolean onLongClick (View v) {Toast. makeText (EasyJavaActivity. this, "Long prompt: You have pressed for a while", Toast. LENGTH_LONG ). show (); return true ;}});

Now, Kotlin cannot call the toast function. Java has to be able to bring back the game. But what should I do if Kotlin is shouting "Let's see me ":

Btn_toast_long.setOnLongClickListener {longToast ("Long prompt: You have pressed for a while"); true}

I did not think that Kotlin has another longToast trick. It only has four more letters, so Kotlin should be a small winner.

 

After five rounds of competition, Kotlin won a big victory, and Java broke into the Army. The direct tutor sighed, "the waves in the Yangtze River pushed forward, and the waves died on the beach ". The above section describes several common Kotlin usage. Starting from the next article, we will systematically explain the basic syntax knowledge of Kotlin.


__________________________________________________________________________
This article has now been published to the Public Account "Old Europe says android", scan the QR code below, or directly search the Public Account "Old Europe says android" to add attention, read technical knowledge faster and more conveniently.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.