“Hello, Kotlin!” in Android


There are two ways you can get Kotlin for the Android studio. The simplest way to get Kotlin support is to download Android Studio 3.0 Preview (Canary version). Android Studio 3.0 comes with Kotlin bundled in it. You can keep both earlier version of Android Studio and Android Studio 3.0 side by side. If you don’t want to download Android Studio 3.0 then you can still get Kotlin support by installing the plugin.

Installing Kotlin Plugin for existing Android studio version (which is not a version 3.0) -
Go to Android Studio > Preferences > Plugins. You will see the following screenshot. Tap on Install JetBrains plugin button.

Installing Kotlin Plugin for existing Android studio version (which is not a version 3.0) -
Go to Android Studio > Preferences > Plugins. You will see the following screenshot. Tap on Install JetBrains plugin button.

Then it will ask you for the plugin to be installed from JetBrains plugins list. As shown in the below screenshot, search for Kotlin and tap on Install button to install Kotlin plugin.

Once the plugin is installed it will ask you to restart the Android studio. Restart it and you have Kotlin plugin in your Android Studio.

We will use Android Studio 3.0 for the “Hello World” program in Kotlin.

Create New Project with Kotlin

You can easily create a new project in Kotlin with few seconds using Android Studio 3.0.

  • If you have a welcome screen open for Android Studio 3.0 then click on Create new project. You have to then check Include Kotlin Support. Click on Next button to complete project setup.
  • If you already have Android project open, go to File > New > New Project and follow the same step as mentioned in #1.

Once your project is created, you will see MainActivity with “.kt” extension instead of Java. Your MainActivity code in Kotlin looks like -

package com.hellokotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

If you run the default app, you will see “Hello World!” label displayed at center of the screen. Hola!! You just created your first “Hello world” Android Application in Kotlin. We can go one step further and create button and implement its click listener.

  • Change Label element in main.xml file to Button and set its text to “Tap me!”.
  • Go to MainActivity.kt file.
  • Create variable for the button as
val tapMeBtn = findViewById(R.id.btnTapMe) as Button
  • Implement Onclicklistener as
tapMeBtn.setOnClickListener(View.OnClickListener {
 Toast.makeText(this, "Hello Kotlin!", Toast.LENGTH_SHORT).show()
})

That’s it!! If you run the application, you will see “Tap me!” button on the screen. Tap on the button and it will show Toast message saying “Hello Kotlin!”.