Home »
Kotlin
OnClickListners - Trigger Button click events using kotlin | Android with Kotlin
By IncludeHelp Last updated : December 04, 2024
OnClickListners Event
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.
Ways to Use OnClickListeners in Android
Here are the various ways in which we can use OnClickListners:
1. Simplest Way Using setOnClickListener<
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 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. Kotlin Style Syntax
button.setOnClickListener({
v->
textView.text = "Clicked"
v.setBackgroundColor(Color.RED)
})
Here v is object of the referenced View.
4. Referencing Current View
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.