Overview
Google has recently announced to provide first-class support to Kotlin programming language starting from Android studio 3.0. Considering the buzz which is started from Kotlin’s introduction into Android world, it seems that Kotlin is here to stay for a long time and should be given more importance.
This series of blogs is aimed to make the android developers friendly with the Kotlin.
Configuring Kotlin library with older android studios:
Android studio 3.0 comes with Kotlin support. But to get Kotlin in android studio below 3.0, we need to configure the library manually in the studio.
Steps
- Install Kotlin plugin by browsing JetBrains plugins in Preferences option of the Main menu and restart the studio.
- Now, configure Kotlin in the project from Tools menu.
Now, we can convert complete java file into kotlin file by selecting ‘Convert Java File to Kotlin File’ option from Code menu.
Farewell to findViewById
Kotlin provides a plugin for android extension which makes it much easier to access xml contents into kotlin file.
We just have to add
apply plugin: ‘kotlin-android-extensions’
in the gradle file of our app.
Also include
import kotlinx.android.synthetic.main.activity_main.*
in kotlin file, if the studio doesn’t do it automatically.
That’s it. Now we can access our xml views just by writing their ids in kotlin file.
<TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" />
TextView defined in xml with the id ‘tv’ can be accessed in kotlin file using just its id i.e. ‘tv’
tv.text = "Hello"
Conclusion
Thus, seeing a buzz about Kotlin among Android guys at Google and the excitement among the developers makes sure that Kotlin thing is here to stay and we should get adapted to it quickly