How to set OnClickListener on a Button in Kotlin Android - Display Toast




Today we are going to look on to display a Toast message on Button click using Kotlin by using OnClickListener on it.
If you guyz are not yet familier with Kotlin check out this post.

So now lets get started with creating our layout file i.e.
activity_main.xml

So, now we are done with creating our layout file, by adding this we have now generated the onClick method for Button but now also it will not do anything we are expecting. So let's head over to creating OnClickListener() here it is


In Android, Toast is a notification message that pop up, display a certain amount of time, and automtaically fades in and out, most people just use it for debugging purpose.

Just Copy and pase all the code to yours and you are all done... there is nothing else to do.

After adding the above code in your MainActivity.kt file your toast message is now created which will display a message "This is a Toast Message" by clicking on the button. Congrats your application now display a toast message on button click, so now run the application in your Emulator or ADB whatever you use. here is the full code for the Toast.

activity_main.xml

MainActivity.kt

For more Toast Example head Over to HERE.
If you have any questions regarding this tutorial and else, let me know in the comment box below.

Thanks...

Follow me on:

Comments