Kotlin setOnClickListener Tutorial

Android button is a UI element generally used to receive user actions as input. In this tutorial, we shall learn to set OnClickListener for button.

Create an Android Application with Kotlin Support and replace activity_main.xml and MainActivity.kt with the following content

<?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="com.farizgaskin.myapplication.MainActivity">
    <LinearLayout
        android:id="@+id/ll_main_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">
        <Button
            android:id="@+id/btn_click_me"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Click Me"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>
package com.farizgaskin.myapplication
 
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
 
class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // get reference to button
        val btn_click_me = findViewById(R.id.btn_click_me) as Button
        // set on-click listener
        btn_click_me.setOnClickListener {
            // your code to perform when the user clicks on the button
            Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
        }
    }
}

Build and Run the Android Application. Click on the ‘Click Me’ button.

Following is the screenshot to demonstrate the setOnClickListener for Button

Conclusion

We hope you enjoyed this tutorial. See you next time!

Leave a Reply

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