The application of Kotlin in Android engineering

Source: Internet
Author: User

The application of Kotlin in Android engineering

@author ASCE1885 's Github book Weibo CSDN
Original link

Brief introduction

Kotlin is an open-source programming language designed by JetBrains, which is becoming increasingly popular among Java developers. Kotlin is often touted as a Java successor, and compared to Java, Kotlin offers richer development experience because it is more modern, expressive, and informative.

If you're looking for an alternative programming language for Android development, try Kotlin. With Kotlin, you can easily replace Java in Android Engineering or mix it with Java.

This article will next describe how to use the Kotlin and Kotlin plugins in Android Studio engineering.

Front-facing conditions

Before you continue this article, you first need to complete the following two things:

    • Update your andoid studio to the latest version
    • Understand the basic syntax of Kotlin

If you are unfamiliar with the Kotlin programming language, it is recommended to read the first section of the Kotlin Guide.

1. Installing the Kotlin Plugin

In the Quick Start menu of Android Studio, select Configure>plugins:

In the open page, click Install JetBrains plugin at the bottom ... :

Select or search Kotlin Extensions for Android in the plugins list and click the Install Plugin button in the right window:

Since this extension relies on the Kotlin plugin, a dialog will pop up prompting us to download it at the same time and click the Yes button to start the plugin download:

When the download installation is complete, restarting Android Studio activates the plugin.

2. Create Kotlin Activity

In Android Studio, right-click the project package name in the pop-up menu, select New>kotlin File:

In the dialog box that pops up, enter the name of the activity and select class from the Type drop-down list. We named the name mainactivity:

When the class is created, you will see a warning that prompts you to configure the app module to support Kotlin:

Click the link to the warning bar and click the OK button in the popup dialog box to select the default Kotlin plugin version:

In order to configure your engineering support, the Kotlin,kotlin plugin modifies the Build.gradle file. Click the Sync Now button to apply these changes:

Here, the configuration of the project has been completed. Let's go back to the Kotlin class we just created to start Kotlin programming.

3. Using Kotlin

To keep the example simple, we'll show you how to create an activity that contains a textview for displaying string strings.

Make sure your class inherits from the activity and overrides its OnCreate function. Of course, you have to use the Kotlin way to achieve. If you are unfamiliar with Kotlin, it is recommended that you activate the code generation feature of Android Studio by using the shortcut key control+o to get the correct function signature:

After the build, our class should look like this:

com.hathy.kotlinsampleimport android.app.Activityimport android.os.Bundlepublic class MainActivity: Activity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)    }}

Create a read-only instance of TextView using the Val keyword:

val myMessage = TextView(this)

Call TextView's SetText function to set the string to display, and then call Setcontentview to set the TextView to it:

myMessage.setText("Hello")setContentView(myMessage)

As in Java activity, you also need to declare kotlin activity in the Androidmanifest.xml file so that the Android system can recognize it. If this is the only activity in your project, then the manifest file looks like this:

<activity android:name=".MainActivity">    <intent-filter>        <action android:name="android.intent.action.MAIN"/>        <category android:name="android.intent.category.LAUNCHER"/>    </intent-filter></activity>

Now you can run the app on your Android device or emulator. Although the Kotlin compiler is slightly slower than the Java compiler, you may not notice a significant change in compilation time.

4. Using the Kotlin android extension

Kotlin's Android extension allows developers to treat the components defined in the activity's XML layout file as if they were the activity attributes. In other words, if you use this plugin, you will no longer need to call Findviewbyid. These properties are therefore referred to as composition attributes (synthetic properties).

To use this feature in your project, you need to include org.jetbrains.kotlin:kotlin-android-extensions as a build script dependency in the app module's Build.gradle file. Do not forget to click the Sync Now button to synchronize this change to the project:

buildscript {    dependencies {        "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"    }}

Now let's create a similar activity created with the previous step, but use the layout XML file to define the TextView. Create a layout XML file and name it another_activity.xml. In this file, define Textview,id as Mymessage:

<?xml version= "1.0" encoding= "Utf-8"?><linearlayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  android:orientation  =" vertical " android:layout_width  = "match_parent"  android:layout_height  = "match_parent" ;     <TextViewandroid:layout_width="Wrap_content"android:layout_height= "Wrap_content" android:textappearance="? Android:attr/textappearancelarge"android:text="Large Text "android:id=" @+id/mymessage " />                                        </linearlayout>

Create another Kotlin class anotheractivity, inherit from activity and override the OnCreate function, as follows:

com.hathy.kotlinsampleimport android.app.Activityimport android.os.Bundlepublic class AnotherActivity: Activity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)    }}

Call Setcontentview in the OnCreate function and set the layout XML file you just created to it:

setContentView(R.layout.another_activity)

Now, instead of using Findviewbyid, you can import TextView using the following code snippet:

import kotlinx.android.synthetic.another_activity.myMessage

If there are other components in the layout file, you can import them all at once using the following statement:

import kotlinx.android.synthetic.another_activity.*

Now you can access the TextView by using the ID, just as the TextView is a property of the activity class. For example, modify the string displayed by TextView:

myMessage.setText("Hello")
5. Convert the Java class to Kotlin

We can use the Kotlin plugin to convert existing Java classes into Kotlin classes. To try this feature, first create the Java class as shown below, which is a simple activity that prints the sum of two integers:

publicclass YetAnotherActivity extends Activity {    privateint a,b;    @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        a=10;        b=20;        Log.d("MESSAGE""The sum is "+(a+b));    }}

Use the shortcut key Control+alt+shift+j, or choose menu Code>convert Java file to Kotlin file:

The converted Kotlin class is as follows:

publicclassActivity() {    privatevar0    privatevar0    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        10        20        Log.d("MESSAGE""The sum is " + (a + b))    }}

In addition to the file content changes, the file's extension is also changed from. java to. kt.

Summarize

In this article we learned how to use Kotlin in Android engineering by installing the Kotlin plugin and the Kotlin Android extension in Android Studio. Since Kotlin and Java are largely interoperable, if you're still learning Kotlin, it's a good idea to gradually apply it to your Android project.

To learn more about Kotlin, I recommend browsing the Kotlin guide. The start section will help you get acquainted with the new language as soon as possible.

Appreciation of the beauty of the end of Wen

The application of Kotlin in Android engineering

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.