First Kotlin + Anko Application

Welcome to Kotlin SG! This is my first post for beginner like me. :-) Please skip this page, if you are expert.

Quick Start

Download tools

1
note the version of AS must above 3.0 in order to support kotlin by default

download Android Studio 3.0 BETA 2 from Android

Learn kotlin language: Learning

Create Android Project

check Include Kotlin support

select target android devices

add an default activity to mobile

configure activity [Note: we don’t want xml layout so uncheck generate layout file]

Enable Anko

1
compile "org.jetbrains.anko:anko:0.10.1"

edit your build.gradle and then click on “Sync Now” to complete this step

More info: Anko

Create a anko component for main activity to replace xml

New -> MainComponent kotlin file and coding is listed as following:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package it.sg.helloword
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.coroutines.onClick
/**
* Created by james on 28/8/17.
*/
class MainComponent: AnkoComponent<MainActivity>{
override fun createView(ui: AnkoContext<MainActivity>)=with(ui){
verticalLayout {
val name = editText()
button("Say Hello") {
onClick { toast("Hello, ${name.text}!") }
}
}
}
}

amend your main activity and coding is listed as following:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package it.sg.helloword
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import org.jetbrains.anko.setContentView
/**
*
*
* Created by james on 28/8/17.
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MainComponent().setContentView(this)//no more xml
}
}

Run your first application and enjoy