Android Button On Click

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
}
private lateinit var binding: ActivityMainBinding
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

--

--

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
Kevin FOO

Kevin FOO

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