The following code does exactly what I want it to.
fun onButtonClick(@Suppress("UNUSED_PARAMETER") v: View) {
val intent = Intent(this, ImageActivity::class.java)
val bundle = Bundle()
orangeButton.setOnClickListener{
val parcel:ImageUrl = IMAGE_URL_ORANGE
bundle.putParcelable("key", parcel)
intent.putExtra(IMAGE_BUNDLE_NAME, bundle)
startActivity(intent)
}
redButton.setOnClickListener{
val parcel:ImageUrl = IMAGE_URL_RED
bundle.putParcelable("key", parcel)
intent.putExtra(IMAGE_BUNDLE_NAME, bundle)
startActivity(intent)
}
greenButton.setOnClickListener{
val parcel:ImageUrl = IMAGE_URL_GREEN
bundle.putParcelable("key", parcel)
intent.putExtra(IMAGE_BUNDLE_NAME, bundle)
startActivity(intent)
}
}
The problem is the behaviour is almost identical in any of the three cases. How do I refactor it? I tried the following but it causes the application to crash.
fun onButtonClick(@Suppress("UNUSED_PARAMETER") v: View) {
val intent = Intent(this, ImageActivity::class.java)
val bundle = Bundle()
lateinit var parcel:ImageUrl
orangeButton.setOnClickListener{
parcel = IMAGE_URL_ORANGE
}
redButton.setOnClickListener{
parcel = IMAGE_URL_RED
}
greenButton.setOnClickListener{
parcel = IMAGE_URL_GREEN
}
bundle.putParcelable("key", parcel)
intent.putExtra(IMAGE_BUNDLE_NAME, bundle)
startActivity(intent)
}
I should probably use some kind of IF statement, but how do I find the ID of the clicked button?