Kotlin Button OnClickListener

Kotlin Button OnClickListener | Android Studio Example

In this onClickListener Kotlin tutorial we will discuss with examples how can we register an OnClickListener on a view in Android using Kotlin language. Before I start telling about Kotlin Button OnClickListener lets first discuss what is an Android button OnClickListener. I will be using OnClickListener on Android TextView and Button.

What is OnClickListener in Android Studio?

OnClickListener is a method in Android. It is a public method and it belongs to the View class. The Button class in Android extends the View class so it can use/call setOnClickListener method.

 

What is an Android Button?

A Button in android is a View or a user interface that performs an action when clicked by the user. When a user taps or clicks the button it performs the specific action and the OnClickListener method performs the given task.

 

Kotlin Button OnClickListener:

1- Create a new Android Studio Project and name it “OnClickListenerExample”. Also, you can give any name of your choice.

 

activity_main.xml

 

2- Change the default Constraint Layout to Relative Layout. Normally, it is easier to work with Relative Layout.

3- We will take a TextView and Button in our activity_main.xml file. We assign ids to both the views and width and height should be “wrap_content”.

 

 

4- After all the above coding, this is how our final activity_main.xml file will look like.

 

 

5- After working with our TextView and Button now we will apply OnClickListener methods on our views in MainActivity.kt file.

 

MainActivity.kt

 

6- In our MainActivity.kt file now we apply OnClickListener methods on our TextView and Button widget like this. Our final MainActivity.kt file will be like this.

 

 

This is how we use OnClickListener in Android using Kotlin language. If you see the code you will see a small difference on the OnClickListener performed on both views. After that on Button I used setOnClickListener with { }. Then, put my code into the body of the block.

 

 

But, on TextView I used setOnClickListener as a method and then inside the body of that method, OnClickListener is placed on that view with View.OnClickListener.

 

 

OUTPUT

 

 

 

 

"<yoastmark

 

"<yoastmark

 

"<yoastmark

 

Since, I have used TextView Android and Button Android in this example. So both ways are easy to use and you can perform OnClickListener on any View using this method. I hope this tutorial helps you to understand the Kotlin Button OnClickListener method in a good way. Also you you have learnt how to use Android Studio Kotlin features.

If you like this Android button onClickListener tutorial share it with your friends and do comment below in comments section. Have Fun 🙂

 

 

     People Also Read

 

Leave a Comment

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