Reputation: 937
In my app I have situation like this:
videoImage.setOnClickListener {
menuClickListener?.videoListClicked()
}
videoText.setOnClickListener {
menuClickListener?.videoListClicked()
}
Both my listeners have the same effect and I consider this boilerplate code. This situation occurs relatively often, so I would like to know the MOST ELEGANT AND BEST solution for these situations.
Upvotes: 0
Views: 51
Reputation: 5980
There are many solutions to this, the most elegant really being a matter of opinion. However I think these two are the most concise.
OnClickListener
You could declare an OnClickListener
that you use for both cases, so something like this:
val listener: (View) -> Unit = { ... }
videoImage.setOnClickListener(listener)
videoText.setOnClickListener(listener)
You could redirect the clicks to a different function:
videoImage.setOnClickListener { sharedClickFunction() }
videoText.setOnClickListener { sharedClickFunction() }
If you had more than a few views, you could also put them in an array and iterate through, but this seems a bit excessive. Something like this:
arrayOf(videoImage, videoText).forEach {
it.setOnClickListener { ... }
}
Upvotes: 2