How to set up OnClickListener to a group of imagebutton in Android

37 Views Asked by At

I knew how to set up OnClickListener to one image button. But how do you set up a OnClickListener to one group of image buttons, such as 10 buttons.

1

There are 1 best solutions below

1
Lowae On
private val imageButtonClickListener = object : OnClickListener {
    override fun onClick(v: View?) {
        v ?: return
        when (v.id) {
            // switch by id
            R.id.image_button1 -> {
                
            }
        }
    }
}

Then create a Collections addAll image buttons. For example:

    val imageButtons = arrayOf<ImageButton>()
    imageButtons.forEach {
        it.setOnClickListener(imageButtonClickListener)
    }