Application of Kotlin in Android project and kotlinandroid Project

Source: Internet
Author: User

Application of Kotlin in Android project and kotlinandroid Project
Application of Kotlin in Android Engineering

@ Author ASCE1885 Github short book Weibo CSDN
Original article link

Introduction

Kotlin is an open-source programming language designed by JetBrains. It is becoming increasingly popular among Java developers. Kotlin is often hailed as the successor of Java. Compared with Java, Kotlin provides richer development experience because it is more modern, more expressive, and more informative.

If you are looking for an alternative programming language developed by Android, try Kotlin. With Kotlin, you can easily replace Java in the Android project or use it with Java.

This article describes how to use the Kotlin and Kotlin plug-ins in the Android Studio project.

Prerequisites

Before continuing this article, you must first complete the following two tasks:

  • Update your Andoid Studio to the latest version.
  • Understand the basic syntax of Kotlin

If you are not familiar with the Kotlin programming language, you are advised to read the first chapter in the Kotlin guide.

1. Install the Kotlin plug-in

In the Quick Start Menu of Android Studio, choose Configure> Plugins:

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

In the plug-in list, select or search For Kotlin Extensions For Android and click the Install Plugin button in the right window:

Because this extension depends on the Kotlin plug-in, a dialog box will pop up prompting us to download it at the same time. Click the Yes button to start downloading the plug-in:

After the download and installation are complete, restart Android Studio to activate the plug-in.

2. Create a Kotlin Activity

In Android Studio, right-click the project package name and choose New> Kotlin File from the context menu:

In the displayed dialog box, enter the Activity name and select Class from the type drop-down list. We name it MainActivity:

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

Click the link to the warning prompt bar. In the displayed dialog box, click OK to select the default Kotlin plug-in version:

To configure your project to support Kotlin, The Kotlin plug-in modifies the build. gradle file. Click Sync Now to apply the changes:

At this point, the project configuration is complete. Let's go back to the Kotlin class we just created to start Kotlin programming.

3. Use Kotlin

To keep the example simple, we will show how to create an Activity that contains a TextView used to display a String.

Make sure that your class inherits from Activity and override its onCreate function. Of course, you must use the Kotlin method. If you are not familiar with Kotlin, we recommend that you use the Control + O shortcut to activate the code generation function of Android Studio to obtain the correct function signature:

After generation, our class should be as follows:

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

Use the val keyword to create a read-only instance of TextView:

val myMessage = TextView(this)

Call the setText function of TextView to set the string to be displayed, and then call setContentView to set TextView to it:

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

Just like 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, the manifest file looks as follows:

<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 this app on your Android device or simulator. Although the Kotlin compiler is a little slower than the Java compiler, you may not notice significant changes in the Compilation Time.

4. Use the Android extension plug-in of Kotlin

Kotlin's Android extension allows developers to treat components defined in the XML layout file of an Activity as they do with Activity attributes. That is to say, if you use this plug-in, you no longer need to call findViewById. These attributes are therefore called the synthesis properties ).

To use this feature in a project, add org. jetbrains. kotlin: kotlin-android-extensions to the build. gradle file of the app module as the build script dependency. Don't forget to click the Sync Now button to synchronize this change to the project:

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

Now let's create an Activity similar to the previous step, but use the layout XML file to define TextView. Create a layout XML file and name it another_activity.xml. In this file, define TextView with the id 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">    <TextView        android: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 the Activity and override the onCreate function. The implementation is as follows:

package 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, you can use the following code snippet to import TextView, instead of using findViewById:

import kotlinx.android.synthetic.another_activity.myMessage

If other components exist in the layout file, you can use the following statement to import them all at once:

import kotlinx.android.synthetic.another_activity.*

Now you can access TextView by using id, just as this TextView is an attribute of the Activity class. For example, modify the string displayed in TextView:

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

We can use the Kotlin plug-in to convert existing Java classes to Kotlin classes. To try this feature, first create the following Java class, which is a simple Activity that prints the sum of two integers:

public class YetAnotherActivity extends Activity {    private int a,b;    @Override    protected void onCreate(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 select the menu Code> Convert Java File to Kotlin File:

The converted Kotlin class is as follows:

public class YetAnotherActivity : Activity() {    private var a: Int = 0    private var b: Int = 0    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        a = 10        b = 20        Log.d("MESSAGE", "The sum is " + (a + b))    }}

In addition to file content changes, the file extension also changes from. java to. kt.

Summary

In this article, we learned how to use Kotlin In the Android project by installing the Kotlin and Kotlin Android extensions in Android Studio. Since Kotlin and Java are highly interoperable, if you are still learning Kotlin, it is best to gradually apply it to your Android project.

To learn more about Kotlin, I suggest you visit the Kotlin guide. The first chapter will help you familiarize yourself with the new language as soon as possible.

Appreciation of meitu at the end of the article

Related Article

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.