
Kotlin Android – Set OnClickListener for Button
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([email protected], "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([email protected], "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.
❮ PreviousNext ❯
Most Read Articles
Learn how to listen for Text Changes in EditTextProgram to get Screen Width and HeightStep by step process to Add External Jar to Android ProjectKotlin Tutorial - Learn Kotlin Programming Language from basicsAndroid Game Development BasicsTop 50 Kotlin Interview QuestionsHow to Learn Programming? Best Guidelines➥ PDF Download - Kotlin OnClickListener - SetOnClickListener for Button in Kotlin AndroidSours: https://www.tutorialkart.com/kotlin-android/set-onclicklistener-button-kotlin-android/How to add onClick to RecyclerView list items in Kotlin
If you are here chances are you already know how to create a RecyclerView, if not take a look at How to create a RecyclerView with custom Adapter in Kotlin.
Overview
Kotlin has higher order functions, which are functions that can have functions as parameters or return functions. So the idea here is that
- Create a function that handles the click event in the UI(Activity/Fragment). The reason you want to create a function here is because list item clicks usually result in UI changes like moving to a different Activity/Fragment, show a Toast/Snackbar, etc.
- Pass this function as argument to the adapter followed by passing the function again to the ViewHolder while creating them.
- In the ViewHolder make the ViewHolder class implement followed by implementing the required method. In the method call the function.
Now when a list item is clicked, the ViewHolder handles the click and calls the method defined in our Activity/Fragment.
As an example I will be adding onClick to RecyclerView in a simple app that displays a list of Github repositories.
Step 1: Create a function that handles click in the UI
Here I am just displaying a Toast, you may navigate to another Activity or Fragment.
Step 2: Add a new function as argument to the Adapter
Change signature of the Adapter so that it accepts a function as an argument.
Now make sure to pass to the adapter in the UI.
Step 3: Add a new function as argument to the ViewHolder
Similarly change the ViewHolder parameter and accept a function. Also implement and implement the method. Finally call the function inside it like so:
Hopefully you feel more comfortable with adding to RecyclerViews. If you find any errors, have feedback or just want to say hi please don’t hesitate to leave a comment below.
In this tutorial, we’ll learn how to create a Button in Android apps using Kotlin programming.
Android Button Overview
Android Button class extends TextView. Button is a UI widget that is 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 the Android Studio Project.
Creating a Button in XML Layout
- The is used to set the text inside the button. By default text is displayed in capital letters.
- is used to define the Kotlin function to be invoked in the activity when the button is clicked. It is a click listener.
- The is used to set the background color/drawable on the Button.
Tip: To prevent displaying all letters in captial, use the attribute
For more details on how to customize your Buttons in XML Layout refer to the Android Buttons Tutorial.
Button Click Listeners
We can set button listeners programmatically too. Following are the two major listeners:
- – triggers when a button is clicked.
- – triggers when a button is pressed for a longer duration.
Following code snippets has the setOnClickListener set over a button.
The above code can be converted in a lambda expression to make it short.
Similarly, a setOnLongClickListener can be defined in the following manner.
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.
Android Button using Kotlin
We’ll be developing an application that increments the counter of the TextView on a Button click. We will use Kotlin to create the button. We’ll also learn about the different Button click handlers.
1. 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.
2. Kotlin Button Code
The activity_main.layout file looks like the following code.
We’ve used LinearLayout that 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 .
The function is defined in the MainActivity.kt Kotlin class.
The code for the MainActivity.kt class is given below.
Important Points:
- statement automatically gets the view IDs from the xml in our class. Hence saving us from using findViewById.
- The is triggered when the is clicked. The parameter must be defined in the function declaration.
- Create a Button programmatically and set it in the parent view(LinearLayout here) using the following code.
- Instead of calling member functions on the Button class, we can use lambda expression.
- The is used to define the width and height of the button. The sets the width/height equal to the linear layout. wraps the view to the size of the content.
- We can set the id programmatically under res | values | ids.xml.
- We’ve defined the interface in our class. Hence we need to override its onClick() function.
- Inside the function, we use the Kotlin when statement, which is equivalent to switch in other languages.
- For the function to be triggered, you must register the over the button with the interface using the context().
Output:
Download Project: AndroidlyButtons
Kotlin Android Button
next →← prev
Android Button is a push button used to perform events on its click. It is a UI component comes under the android.widget.Button class. To learn more about Android Button refers to Android Button Example
Using Kotlin, we can perform events on Android Button though different ways, using:
1. Implement the setOnClickListener of Button
2. Implement the View.OnClickListner and override its function
3. Adding the onClick attribute of Button in layout file and implement its function.
4. Create a Button programmatically and set it on the layout
Kotlin Android Button Example
In this example, we will create the Button and performs event on them. Clicking on the Button, display a toast message.
activity_main.xml
Add the three Button from the Widgets palette in the activity_main.xml layout file. Its code is given below. The Button of id button3 added the onClick attribute and its function name is implemented in MainActivity class file.
MainActivity.kt
Add the following code in the MainActivity.kt class. In this class, we implement the setOnClickListener listener on the button, implements the OnClickListener of View class (View.OnClickListener) and override its function onClick. In this class, we also create a Button programmatically (button4), define its properties and set it on the layout.
Output:



Next Topic#
← prevnext →
Kotlin onclick
We cannot use it, somehow for the evil of people. Any member of our order who uses his magic in scruffy and evil intentions, as well as in order to harm any person, in. The same second lose I woke up when the sun was already high above the horizon.
Creating a RecyclerView that handles Click Events in Android Studio (Kotlin 2020)So, I lied, it's not the sea. And what is it. - I asked, having already guessed by example what happened there.
Similar news:
- Melvin park chapin
- Splash clipart
- Krithi shetty
- Pig silhouette free
- Mod pizza indeed
- Lynz way
- Ferrari horn button
- Infantry co watch
- Annoying orange hentai
- Sonic figure
Damn, you dick recognize when you are serious, and when not. - Max said with delight, almost with a kick, opening the door to the hotel lobby. While I was laying out and hanging my. Things, the girlish hubbub again floated down the floor, but it wasnt possible to be left alone.