Kotlin setOnClickListener for Button
Android Button widget is a UI element generally used to receive user actions as input. You can click on a Button, long press, etc.
In this tutorial, we shall learn to set OnClickListener for Button.
Code – Button.setOnClickListener()
Following code helps you to set on-click listener for Button.
// get reference to button
val btn_click_me = findViewById(R.id.btn_click_me) as Button
// set on-click listener
btn_click_me.setOnClickListener {
Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
}
What we have done here is, we got the reference to the Button and then used setOnClickListener method to trigger an action when the button is clicked.
Example – Kotlin Androide Button.setOnClickListener()
Now we shall look into the layout xml file and Activity(Kotlin file) to set OnClickListener for a Button.
Create an Android Application with Kotlin Support and replace activity_main.xml and MainActivity.kt with the following content.
activity_main.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="com.tutorialkart.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>
MainActivity.kt
package com.tutorialkart.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. You would see the Android screen as shown in the following screenshot.
Tao on ‘Click Me’ button.
Button.setOnClickListener() will be triggered and the code in this setOnClickListener{} block will run.
Conclusion
In this Android Tutorial – Kotlin Button OnclickListener, we have learnt to set OnClickListener for Button in Kotlin Android using Button.setOnClickListener() method.