Home » Kotlin

OnClickListners - Trigger Button click events using kotlin | Android with Kotlin

In this article, we will discuss about how to trigger click events on android Views (Buttons, Text views etc)?
Submitted by Aman Gautam, on October 09, 2018

The event is a very important part of any application which makes it user intractable. It may be generated when we click on any view in Android. To trigger click events on any view, we have OnClickListners.

Here are the various ways in which we can use OnClickListners:

1) Simplest way is writing code under setOnClickListener{ } which you want to execute on button(view) click.

	Toast.makeText(applicationContext, "You clicked me.", Toast.LENGTH_SHORT).show()

button is the id of the Button. We have used <id>.setOnClickListener. This can be achieved using view binding in kotlin which we have discussed in previous article. If you are new to view binding, I suggest you to go through previous article once.

2) Kotlin implementation of the Java code

button.setOnClickListener(object: View.OnClickListener {
	override fun onClick(v: View?) {
		textView.text = "Clicked"

If you want to use that view during the click event, use this. In this we have an object of view, you can use that view object to make changes to the particular view if required.

3) Similar to 2 but in kotlin style

	textView.text = "Clicked"

Here v is object of the referenced View.

4) We can also use it to reference current view in kotlin

	textView.text = "Clicked"


So in this article, we came to know about various ways in which we can use click events on android views. If you feel any doubt just write down to the comment section.


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.