Search code examples
androidkotlinmaterial-designandroid-togglebutton

Both buttons are checked in MaterialToggleButton Android while only one should


I have a MaterialButtonToggleGroup like this

<com.google.android.material.button.MaterialButtonToggleGroup
            android:id="@+id/toggleGroup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            app:singleSelection="true">

            <com.google.android.material.button.MaterialButton
                android:id="@+id/bYes"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="YES" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/bNo"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="NO" />
        </com.google.android.material.button.MaterialButtonToggleGroup>

I am listening to the changes happening on this ToggleGroup like this

toggleGroup.addOnButtonCheckedListener { group, checkedId, isChecked ->
//            println("checkedId ${checkedId} $isChecked")
            if (checkedId == R.id.bYes){
                println("yes is checked "+1)
            }else{
                println("no is checked "+0)
            }
        }

But what's happening is, both buttons are checked when I am just switching from YES to NO. I am getting the logs like this

I/System.out: yes is checked 1
I/System.out: no is checked 0

whenever I switch from YES to NO. Shouldn't this only give me the button that is checked not the button that is unchecked?

Any help would be appreciated.


Solution

  • You have to filter the checked button with the isChecked flag:

    toggleGroup.addOnButtonCheckedListener { group, checkedId, isChecked ->
        if(isChecked) {
            when(checkedId) {
                R.id.bYes -> println("YES is checked")
                R.id.bNo -> println("NO is checked")
            }
        } else {
            when(checkedId) {
                R.id.bYes -> println("YES is not checked")
                R.id.bNo -> println("NO is not checked")
            }
        }
    }