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.

button.setOnClickListener{
	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"
		v?.setBackgroundColor(Color.MAGENTA)
	}
}

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

button.setOnClickListener({
	v->
	textView.text = "Clicked"
	v.setBackgroundColor(Color.RED)
})

Here v is object of the referenced View.

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

button.setOnClickListener{
	textView.text = "Clicked"
	it.setBackgroundColor(Color.RED)
}

Conclusion:

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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.