Android Button On Click

Kevin FOO
2 min readMar 16, 2021

--

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(R.id.button)
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)
setContentView(binding.root)

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

< Back to all the stories I had written

--

--

Kevin FOO

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