Android Button Using Kotlin

Filed Under: Android

In this tutorial, we’ll be using Kotlin in our implementation of Android Buttons in an application. Let’s dive right in.

Overview

Android Button class extends TextView. Buttons are a UI widget used to get click interactions from the user to trigger an action in the application.

A button can be created in the xml layout as well as the Kotlin Activity class in our Android Studio Project.

Creating in our XML Layout


<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Androidly Button"/>
  • android:id is used to set the unique identifier on the Button.
  • android:text is used to set the text inside the button. By default text is displayed in capital letters.
  • android:onClick is used to define the Kotlin function to be invoked in the activity when the button is clicked. Basically, it is a click listener.
  • android:background is used to set the background color/drawable on the Button.
Tip: To prevent displaying all letters in captial, use the attribute android:textAllCaps="false"

For more details on how to customize your Buttons in XML Layout refer to the JournalDev Buttons Tutorial.

Button Click Listeners

Besides using the onClick attribute in XML to trigger a function on button click, we have button listeners set programmatically. Following are the two major listeners:

  • setOnClickListener – triggered when a button is clicked.
  • setOnLongClickListner – triggered when a button is pressed for a longer duration.

Following code snippets has the setOnClickListener set over a button.


button.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                //your implementation goes here
            }
        })

This can be converted in a lambda expression to make it short and sweet.


button.setOnClickListener {   
      textView.text = "Androidly Buttons"
    }

Similarly, a setOnLongClickListener can be defined in the following manner.


button.setOnLongClickListener {
        textView.text = "Androidly Button Long click"
        true
    }

//or
button.setOnLongClickListener {
        textView.text = "Androidly Button Long click"
        false
    }

In the above code, the last statement in each of the expressions is the return statement.

  • If the setOnLongClickListener returns true, it means that the setOnClickListener won’t be triggered.
  • If the setOnLongClickListener returns false, it means that the setOnClickListener will be triggered.

This is known as consuming events. The first case consumes the event.

Let’s jump onto the business part of this tutorial now. We’ll be developing an application that increments the counter of the TextView on a Button click. Furthermore, we’ll see the different click handlers that Buttons has in store as well as create Buttons programmatically in Kotlin.

Project Structure

Create a new Android Studio Project. Ensure that in the initial setup, you enable Kotlin Support. Once you’re done, following is the Project Structure that you shall see.

android-button-project-structure

Code

The activity_main.layout file looks like this:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txtCounter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/number_zero"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="#000" />


    <Button
        android:id="@+id/btnIncrementByOne"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="addOne"
        android:text="@string/increment_by_one" />

</LinearLayout>

We’ve used LinearLayout which holds the views linearly(horizontally or vertically).
It’s recommended to set the strings in the strings.xml file instead of hardcoding them. To fetch a string resource we use @string/name_of_string

android-button-strings-xml

The function addOne(view: View) is defined in the MainActivity.kt Kotlin class.

The code for the MainActivity.kt class is given below.


package net.androidly.androidlybuttons

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), View.OnClickListener {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var androidlyButton = Button(this)
        androidlyButton.apply {
            layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            text = "Double the value"
            setAllCaps(false)
            textSize = 20f
            id = R.id.btnDouble
        }

        androidlyButton.setOnClickListener(this)
        linearLayout.addView(androidlyButton)

        androidlyButton = Button(this)
        androidlyButton.apply {
            layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            text = "RESET"
            textSize = 20f
            setTextColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimaryDark))
            id = R.id.btnReset
            setOnLongClickListener {
                txtCounter.text = 0.toString()
                true
            }
        }
        androidlyButton.setOnClickListener(this)
        linearLayout.addView(androidlyButton)

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btnDouble -> {
                txtCounter.text = (txtCounter.text.toString().toInt() * 2).toString()
            }
            R.id.btnReset -> {
                txtCounter.text = (-100).toString()
            }
            else -> {
            }
        }
    }

    fun addOne(view: View) {
        txtCounter.text = (txtCounter.text.toString().toInt() + 1).toString()
    }
}

  • import kotlinx.android.synthetic.main.activity_main.* statement automatically gets the view IDs from the xml in our class thus saving us from using findViewById.
  • fun addOne(view: View) is triggered when the btnIncrementByOne is clicked.
    The (view: View) parameter must be defined in the function declaration.
  • Create a Button programmatically and set it in the parent view(LinearLayout here) using
    var androidlyButton = Button(this)
    linearLayout.addView(androidlyButton)
    
  • Instead of calling member functions on the Button class, we simply use apply{} lambda expression.
  • layoutParams is used to define the width,height of the button here. MATCH_PARENT sets the width/height equal to the linear layout. WRAP_CONTENT wraps the view to the size of the content.
  • We can set the id programmatically under res | values | ids.xml
    android-button-ids-xml
  • We’ve defined the View.OnClickListener interface in our MainActivity.kt class. Hence we need to override it’s function onClick.
  • Inside the onClick we use the Kotlin when statement which is equivalent to switch in other languages.
  • For the onClick function to be triggered you must register the setOnClickListener over the button with the interface using the context(this).

The output of the above application in action is given below:

android-button-kotlin-output

This brings an end to this tutorial on Android Buttons in Kotlin. You can download the AndroidlyButtons Project Source code from the link below.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages