Android Button On Click

I got tired with the need to search for button on click listener codes each time I am coding Android once in a blue moon and now decided to just document it down.

Create a button
val button: Button = findViewById(
button.setOnClickListener {
Toast.makeText(this, "Hello world", Toast.LENGTH_LONG).show()

Kotlin Synthetics

Just found out there is an easier way to do this with Kotlin Synthetics and somehow it is easier for me to remember than the findViewById method. Unfortunately there are plan to deprecate this in future.

button?.setOnClickListener {
Toast.makeText(this, "Hello world", Toast.LENGTH_LONG).show()

View Binding

To use view binding, you’ll need to enable viewBinding in your module level build.gradle

buildFeatures {
viewBinding true

Declare the binding variable

private lateinit var binding: ActivityMainBinding

Disable existing setContentView using R.layout and use the view binding.

binding = ActivityMainBinding.inflate(layoutInflater)

It is slightly longer than Kotlin Synthetics but still easier to remember than findViewById.

< Back to all the stories I had written

A software engineer, a rock climbing, diving & inline skating enthusiast, a husband, a father.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store