Search code examples
androidfor-loopbuttonkotlinadapter

Kotlin/Android - Only one ToggleButton can be checked


I have a group of ToogleButtons. Inside the adapter I got them in an array:

val groupToggleButtons = arrayOf( holder.one,
                    holder.two,
                    holder.three,
                    holder.four,
                    holder.five,
                    holder.six)

So, in this group of six, only one can be checked. If I press the button holder.two and then the holder.six, the holder.two must be unchecked on time. Get it? I've tried the next logic, but without sucess... the findViewById doesn't work, of course (because is an adapter), but then I don't know what to do, tried a lot a logics... nothing did what I want. Here's the code:

groupToggleButtons.forEach {
    it.setOnCheckedChangeListener { v, isChecked ->
        val buttonId = v.id

        for (i in 0 until groupToggleButtons.size) {
            if (i != buttonId) {
                val buttonToOff = findViewById(i) as ToggleButton
                buttonToOff.isChecked = false
            }
        }
    }
 }

Solution

  • You have to filter from the array all the buttons that are checked and uncheck them:

    groupToggleButtons.forEach {
        it.setOnCheckedChangeListener { v, isChecked ->
            if (isChecked)
                groupToggleButtons.filter { it != v && it.isChecked }.forEach { it.isChecked = false }
        }
    }