Skip to main content

How to Use Kotlin in Your Android Projects

How to Use Kotlin in Your Android Projects


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.
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.
In Android Studio's quick start menu, select Configure > Plugins.

 In the next screen, click Install JetBrains plugin... at the bottom.


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.


 When the installation completes, restart Android Studio to activate the plugins.

In Android Studio, right-click the name of your package and select New > Kotlin File.


 In the dialog that pops up, enter the name of the new 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.


 At this point, your project's configuration is complete. Go back to the Kotlin class you created a moment ago to start coding in 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:
Create an instance of TextView as an assign-once local variable by using the val keyword.
Call its setText method to set the String you want to display and then call setContentView to display the text view.
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:
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.
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.
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.
Create another Kotlin class, AnotherActivity, that extends Activity and override its onCreate method. This is what the implementation should look like:
Call setContentView in the onCreate method to use the layout XML you just created as the layout of this Activity.
Now, instead of calling findViewById to get a reference to the TextView, you can import it using the following code snippet:
If you had more widgets in your layout, you can import all of them using the following code snippet:
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:

Comments

Popular posts from this blog

Android Logging using Timber Library

  Timber     is a logger with a small, extensible API which provides utility on top of Android's normal Log class. Before  the release, we’ll cleanup the log statements by removing them manually (even though logs can be disabled in release build). This tedious process can be avoided easily by using Timber. Timber provides lots of other options as well. Let’s see how it can be used in our projects to maintain the logs better. 1. Timber Below are few debug statements printed using default Log class. int a = 100 ; Log.e( "TAG" , String.format( "Integer a value is: %d" , a));   String name = "Android Codest" ; Log.e( "TAG" , String.format( "Find source from: %s" , name)); The above same statements can be printed using Timber as below. int a = 100 ; Timber.d( "Integer a value is: %d" , a);   String name = " Android Codest " ; Timber.d( " Find source from : %s" , name); You can notice here, the TAG is not p...

Convert your apk into Android App Bundle

Android App Bundle In Google I/O 2018, a new publishing format has been introduced for Android applications called Android App Bundle. It is a new upload format that includes all your app’s compiled code and resources, but defers APK generation and signing to Google Play. Traditionally, Android apps are distributed using a special file called an Android Package(.apk). How to build an app bundle? You can easily build your app bundle using Android Studio(3.2 Canary 14+) or using command line interface. The generated app bundle will be stored at app/build/outputs/bundle/buildVariant/bundle.aab. Android Studio : Go to Build > Build Bundle(s)/APK(s) and select Build Bundle(s). Console : ./gradlew bundle Dynamic Delivery with Split APKs A fundamental component of Dynamic Delivery is the split APK mechanism available on Android 5.0 (API level 21) and higher. Split APKs are very similar to regular APKs — they include compiled DEX bytecode, resources, and an Android manifest. However, the ...

Push Notification using Firebase in Android

This is a tutorial about sending push notifications to Android through Firebase, based on the new release of Firebase this year (2016). This tutorial shows how to setup the skeleton for sending and receiving push notifications via FCM with instructions on server code. 1. Get started Add a new project or import an existing project to  Firebase console . If you choose to create a new project, you need to set the project name and country. For example, I will call my project Firebase Notification Then select "Add Firebase to your Android app". Set a package name for your app. I only set my package name and omit the SHA-1 because I don't use Firebase for my app's authentication. Click the  ADD APP  button here to download google-services.json. This is an important file and you will need to put it into your app. 2. Add google-services.json to your app folder Replace the google-services.json in your app folder. The Google services plugi...