How to Use Kotlin in Your Android Projects
Introduction
Kotlin, the open source programming language designed by JetBrains, is becoming increasingly popular among Java developers. It is often touted as Java's successor. Compared to Java, it offers a richer development experience, because it is more modern, expressive, and concise.
If you are looking for an alternative programming language for Android development, you should give Kotlin a try. It can easily be used instead of or alongside Java in your Android projects.
In this tutorial, I will show you how to use Kotlin and Kotlin plugins in your Android Studio projects.
Prerequisites
To follow along with me, you need to have:
- the latest version of Android Studio
- a basic understanding of Kotlin syntax
If you're unfamiliar with the Kotlin programming language, then I recommend reading the Getting Startedsection of the Kotlin reference to get up to speed with the language.
1. Installing Kotlin Plugins
In Android Studio's quick start menu, select Configure > Plugins.
Select Kotlin Extensions For Android from the list and click Install Plugin on the right.
Because the plugin depends on the Kotlin plugin, you will be asked to install both. Click Yes to begin the installation.
2. Creating a Kotlin Activity
In Android Studio, right-click the name of your package and select New > Kotlin File.
Activity and select Class from the drop-down list. I've named my class MainActivity.Once the class has been created, you will see an alert asking you to configure your app module to support Kotlin.
Click the link in the alert and, in the dialog that pops up, click OK to choose the default values.
To configure your project to support Kotlin, the Kotlin plugin makes several changes in the build.gradle file. Apply these changes by clicking the Sync Now button as shown below.
3. Using Kotlin
To keep the example simple, I will be showing you how to create an
Activity with a single TextView that displays a String.
Make sure your class is a subclass of
Activity and override its onCreate method. Of course, you have to do that in Kotlin. If you are new to Kotlin, I suggest you use Android Studio's code generation functionality by pressing Control+O to get the method signatures right.
Your class should now look like this:
01
02
03
04
05
06
07
08
09
10
| package com.smit.kotlinsampleimport android.app.Activityimport android.os.Bundlepublic class MainActivity: Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) }} |
Create an instance of
TextView as an assign-once local variable by using the val keyword.
1
| val myMessage = TextView(this) |
Call its
setText method to set the String you want to display and then call setContentView to display the text view.
1
2
| myMessage.setText("Hello Kotlin")setContentView(myMessage) |
Like you would for a Java
Activity, you need to declare your Kotlin Activity in your app's AndroidManifest.xml for it to be recognized by the Android system. If this is the only Activity in your project, your manifest file should look like this:
1
2
3
4
5
6
| <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter></activity> |
You can now compile and run your app on your Android device or emulator. While the Kotlin compiler is slightly slower than that of Java, you are unlikely to see any significant change in your project's build time.
4. Using Kotlin Android Extensions
The Kotlin Android Extensions plugin lets you treat the widgets you define in the layout XML of an
Activity as if they were properties of that Activity. In other words, if you use this plugin, you will never have to call findViewById. These properties are aptly called synthetic properties.
To use this feature in your app, you need to add
org.jetbrains.kotlin:kotlin-android-extensions as a build script dependency in your app module's build.gradle as shown below. Don't forget to click the Sync Now button to sync your project.
1
2
3
4
5
| buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version" }} |
Let's now create an
Activity similar to the one we created in the previous step, but use a layout XML to define the TextView. Create a new layout XML file named another_activity.xml. In the layout XML file, define a TextView with an id of myMessage.
01
02
03
04
05
06
07
08
09
10
11
12
| <?xml version="1.0" encoding="utf-8"?> 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, that extends
Activity and override its onCreate method. This is what the implementation should look like:
01
02
03
04
05
06
07
08
09
10
11
| package com.smit.kotlinsampleimport android.app.Activityimport android.os.Bundlepublic class AnotherActivity: Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) }} |
Call
setContentView in the onCreate method to use the layout XML you just created as the layout of this Activity.
1
| setContentView(R.layout.another_activity) |
Now, instead of calling
findViewById to get a reference to the TextView, you can import it using the following code snippet:
1
| import kotlinx.android.synthetic.another_activity.myMessage |
If you had more widgets in your layout, you can import all of them using the following code snippet:
1
| import kotlinx.android.synthetic.another_activity.* |
You can now access your
TextView using its id as if it were a property of the Activity class. For example, to change the text of the TextView, you can write:
1
| myMessage.setText("Hello kotlin")5. Converting Java Classes to Kotlin
You can use the Kotlin plugin to convert existing Java classes to Kotlin classes. To try this feature, create a new Java class with the following implementation. It's a simple
Activity that logs the sum of two integers.
Convert the Java class to a Kotlin class by pressing Control+Alt+Shift+J, or, from the menu, selecting Code > Convert Java File to Kotlin File.
|
After the conversion, your class will look like this:
01
02
03
04
05
06
07
08
09
10
11
12
| 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)) }} |
You will also notice that the file's extension has changed from .java to .kt.











Comments
Post a Comment