Creating a simple Counter application using Kotlin for Android
In the following tutorial, we’ll be working to create a simple kotlin application for android platform. The tutorial has been divided into 5 steps, each step moving progressively on top of last one.
The app is a simple counter, which on press of a button will keep track of counter and display it on the screen. It’ll reset to zero on press of reset button.
This tutorial assumes, you have a basic working knowledge of android studio and the framework in place.
First, launch the Android Studio and open a new project with an empty activity, and language selected as Kotlin. Once the gradle build finishes, continue with setting up the layout of the application.
An empty Android studio project by default has a TextView set up within a Constraint Layout. So, go ahead and delete the Text View and constraint layout. Pull in a linear layout in place of the it.
Add a new TextView. The text of this will be initially set to zero.
Now add two buttons, one for as a Increment button and another as a Reset button.
onClick function to each of the buttons
The UI will look something like below:
If you have worked with Android before, you must be well aware of the java function, findViewById(int value of Id). We can do this in Kotlin too, but Kotlin comes with a elegant way to handle it. The kotlin android extension plugin, lets you access views from the code by directly using the id of element declared in the XML.
You can set it up by, putting the following lines in your app’s build.gradle file.
After that, it’s as simple as a simple import. Import the following line for the activity_main.xml, in MainActivity.kt and you’re good to go.
Add the following code to MainActivity.kt.
And that’s it. Our application is good to go.
Keep coding! Have fun.