ZOFTINO.COM android and web dev tutorials

Developing Android App in Kotlin

With this tutorial, you can learn how to create kotlin android app project, examine gradle build file and how to reference in activities the views defined in the layout xml and how to add listener to a view using an example app.

For kotlin basics, see kotlin basics tutorial and kotlin classes and objects tutorial.

Create Kotlin Android Project

First install the latest version of android studio, then start android studio, on the android studio welcome screen, click create new project.

On the create-new-project window, enter application name and domain, check include kotlin support check box and click next.

android kotlin create project

On the next screen, leave default settings including minimum SDK and click next.

android kotlin create project select min SDK

Select empty activity and click next.

android kotlin create project empty activity

Then click finish.

android kotlin create project configure activity

It will create android project with empty MainActivity kotlin file (kt) with MainActivity class in it.

Kotlin Android Plugin and Dependencies

Android studio will create build.gradle file in the project and adds kotlin android plugin and dependencies to it. It also adds kotlin android extensions plugin which takes of view binding and caching.

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

    . . . . .

dependencies {

    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    . . . . .
}

Andorid Kotlin Example App

Let’s add elements to layout and code to the main activity to create a screen which allows user to enter tennis match score and view score of a match. The example stores the score data in shared preferences and reads from it.

Match name is used as key and two player’s details including scores are stored as a value. Each player data is separated by a delimiter and each player data containing player name and score are separated by another delimiter. Using these delimiters, scores can be updated.

android kotlin first app example

In the main activity kotlin file, notice that with kotlinx.android.synthetic.main import , view objects defined in the layout can be obtained by just using the view ids. The kotlin file contains two functions which are called from on-click listeners of add and view buttons.

package zoftino.scores

import android.content.Context
import android.content.SharedPreferences
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    lateinit var sharedPref: SharedPreferences

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

        add_score.setOnClickListener { v -> addScore() }
        view_score.setOnClickListener { v -> viewScore() }

        sharedPref = this?.getPreferences(Context.MODE_PRIVATE)
    }

    fun addScore() {
        val match = match_et.text.toString()
        val payerIn = player_et.text.toString()

        val playerScoreIn = payerIn + "-" + sets_won_et.text.toString() + " " +
                games_won_et.text.toString() + " " + points_won_et.text.toString() + " "

        val matchScore = sharedPref.getString(match, "")

        var score: String = ""

        if (matchScore.isBlank()) {
            score = playerScoreIn
        } else {
            val palyers = matchScore.split("|")
            var isUpdated = false
            for (i in palyers.indices) {
                var playerScore = palyers[i]
                if (playerScore.isBlank()) {
                    continue
                }
                var player = playerScore.split("-")
                if (payerIn.equals(player[0])) {
                    playerScore = playerScoreIn
                    isUpdated = true
                }
                score = score + playerScore + "|"
            }

            if (!isUpdated) {
                score = score + playerScoreIn
            }
        }

        with(sharedPref.edit()) {
            putString(match, score)
            commit()
        }

        Toast.makeText(this, "added score", Toast.LENGTH_LONG).show()
    }

    fun viewScore() {
        Toast.makeText(this, sharedPref.getString(view_match_et.text.toString(), ""),
                Toast.LENGTH_LONG).show()
    }
}

Here is the layout xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/score_head_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:text="Add Tennis Match Score"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"  />
    <android.support.design.widget.TextInputLayout
        android:id="@+id/match_til"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/score_head_tv">
        <android.support.design.widget.TextInputEditText
            android:id="@+id/match_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Match"/>
    </android.support.design.widget.TextInputLayout>
    <android.support.design.widget.TextInputLayout
        android:id="@+id/player_til"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/match_til">
        <android.support.design.widget.TextInputEditText
            android:id="@+id/player_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Player"/>
    </android.support.design.widget.TextInputLayout>
    <android.support.design.widget.TextInputLayout
        android:id="@+id/sets_won_til"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/player_til">
        <android.support.design.widget.TextInputEditText
            android:id="@+id/sets_won_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Sets Won"/>
    </android.support.design.widget.TextInputLayout>
    <android.support.design.widget.TextInputLayout
        android:id="@+id/games_won_til"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/sets_won_til">
        <android.support.design.widget.TextInputEditText
            android:id="@+id/games_won_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Games Won"/>
    </android.support.design.widget.TextInputLayout>
    <android.support.design.widget.TextInputLayout
        android:id="@+id/points_won_til"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/games_won_til">
        <android.support.design.widget.TextInputEditText
            android:id="@+id/points_won_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Points Won"/>
    </android.support.design.widget.TextInputLayout>
    <Button
        android:id="@+id/add_score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.Button.Colored"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/points_won_til"
        android:text="Add Score"/>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/view_match_til"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/add_score">
        <android.support.design.widget.TextInputEditText
            android:id="@+id/view_match_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Match"/>
    </android.support.design.widget.TextInputLayout>
    <Button
        android:id="@+id/view_score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.Button.Colored"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view_match_til"
        android:text="View Score"/>
</android.support.constraint.ConstraintLayout>