Skip to main content

How to setup Kotlin in Android Studio

Brief about Kotlin

What I am impressed in Kotlin is Android Extensions. It enables you to remove boiler plate code of setting views. You have bind your view object by calling findViewbyId() but Kotlin supports it just importing kotlinx.android.synthetic..* package. Let's have a look at an example:
res/layout/login.xml

    
    
    
    
    
LoginActivity.kt
package com.ispark.kotlin.login

import kotlinx.android.synthetic.login.*
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import com.ispark.kotlin.R
import kotlin.String

public class LoginActivity : AppCompatActivity() {

    private val LOG_TAG: kotlin.String = "LoginActivity"

    override fun onCreate(savedInstanceState : Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.login)
        setTitle(R.string.pleaseSignIn)

        loginButton.setOnClickListener {
            if (required(loginEditText)){
                Toast.makeText(this, "ID is required", Toast.LENGTH_SHORT).show()
            }

            if (required(passwordEditText)){
                Toast.makeText(this, "Password is required", Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun required(v : TextView) = TextUtils.isEmpty(v?.getText().toString().trim())
}


Where is loginButton member variable? The import kotlinx.android.synthetic.login.* makes it possible. You can use the ID in the layout XML as a member object. What an amazing! There are still other powerful things in Kotlin. I guess you could find them easily if you visit the website.



Setup Kotlin


My testing environment

  • Mac OSX Yosemite(10.10.3)
  • Java 1.7
  • Android Studio 1.2.1.1
  • Gradle 1.2.3

Plugin Installation

Got to Android Studio > Preferences > Plugins and install plugins below:
  • Kotlin
  • Kotlin Extensions For Android

Gradle Builds

project build.gradle

allprojects {
    repositories {
        mavenCentral()
    }
}
module build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.ispark.kotlin"
        minSdkVersion 10
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
        androidTest.java.srcDirs += 'src/androidTest/kotlin'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}


buildscript {
    ext.kotlin_version = '0.11.91.4'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

There are different languages you can use for Android development such as Groovy and Scala. You can also use Java8 Lambda expression by using Retrolambda but I think Kotlin looks like the way to take than any others because it is very similar to Java and you can easily pick up the language. It also works on JVM and provide powerful features other languages have and you can even add your own function to the build in classes like String. Of course, it provides much more powerful Lambda than Java8 and there are many more nice points worthy to check.

Comments

Popular posts from this blog

Apply Kotlin DataBinding to Android Studio Generated Main Activity

I posted how to setup Kotlin and DataBinding in Android Stuido in the last blog (http://marksunghunpark.blogspot.com.au/2017/04/kotlin-binding-library-setup-in-android.html). In this post, I am going to how to use DataBiding in the MainActivity when you create a navigation drawer project from Android Studio templates. Layouts You will have four layouts in app/src/res/layout folder: app/src/main/res/layout/activity_main.xml app/src/main/res/layout/app_bar_main.xml app/src/main/res/layout/content_main.xml app/src/main/res/layout/nav_header_main.xml And activity_main.xml contains all other layout using include layout. You need to have tag in activity_main.xml , app_bar_main.xml and content_main.xml . If you don't have the tag, Binding library cannot recognise the sub layouts properly. Binding library doesn't support toolbar and navigation drawer yet, so you can use using BindingAdapter if you want to use binding library.(But I'm gong to skip this part for simplici

How to test AsyncTask in Android

In Android, test is not as easy as any other platform. Because Android test cannot be run without emulator. Particulary when it comes to AsyncTask or Service, it is difficult to test because they are different type of thread and hard to check their result. Then, how can we ensure the result of AsyncTask valid? AsyncTask is a thread and an asynchnorous as the name means. So, we need to wait for it finishes its job and need to capture the event. Then, when it happens in AsyncTask. It can be one of onBackground() and onPostExecute() methods. It doesn't matter you use onBackground() or onPostExecute() but I prefer onPostExecute(). Anyway, we can test an AsyncTask if we can hook it. Then, how can we hook it? For that, we can use callback pattern. But we need to delay main thread to wait for the AsyncTask's job done because we want to check the result. So the structure for the test would be like: 1. Create AsyncTask A 2. Injection a callback into A 3. Wait until A finish 4.

Let's start Lambda in Android

In Android programming, I think Java & J2EE programming are not that different, we developers put many boiler plate code particularly when we use anonymous instances. Example1. Simple example button1.setOnClickListener(new OnClickListener(){ @Override public void onClick(View view){ //Do something } }); In the above example, what we really need is inside of onClick() method. Other code is actually decorations and we don't want it. How about we can pass just onClick method body as a parameter of setOnClickListener method like below? button1.setOnClickListener(view->{ //Do something }); That's what we have exactly wanted. We can use the code style in Java 8. I think you already might know about Java 8 Lambda but there is no official support for Java 8 in Android 8. It would be awesome we can use it in Android and there is a way to be able to use Lambda in Android as well. You can refer my previous blog to setup RetroLambda in Andro