Search code examples
androidkotlinandroid-buttonmaterial-componentsmaterial-components-android

How to make material toggle button in Android to behave like Switch?


I am using the following material design library

implementation "com.google.android.material:material:1.2.0-alpha01"

And this is how I am implementing my Material Toggle Button

<com.google.android.material.button.MaterialButtonToggleGroup
    id="@+id/toggleBtnGroup"
    app:singleSelection="true"
    android:id="@+id/toggle_button_group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:checkedButton="@+id/leftAlign">

    <com.google.android.material.button.MaterialButton
        id="@+id/leftAlign"
        style="?attr/materialButtonOutlinedStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Left"/>
    <com.google.android.material.button.MaterialButton
        id="@+id/centerAlign"
        style="?attr/materialButtonOutlinedStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Center"/>
    <com.google.android.material.button.MaterialButton
        id="@+id/rightAlign"
        style="?attr/materialButtonOutlinedStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Right"/>

</com.google.android.material.button.MaterialButtonToggleGroup>

Now, as I select other buttons, only 1 button is selected at a time, how can I make sure that if user selects the selected button again, it does not gets unselected. So in essence, I want atleast one of these buttons to be selected at a particular time. Material Button Toggle

How would one do this?


Solution

  • To implement this, do something like this :-

    //We are adding a button checked listener to the toggle group
    toggleBtnGroup.addOnButtonCheckedListener { group, checkedId, isChecked ->
        if (isChecked){
            //Do something
        } else {
            //Something is unchecked, we need to make sure that all the buttons are not un-selected
            if(-1 == group.checkedButtonId){
                //All buttons are unselected
                //So now we will select the button which was unselected right now
                group.check(checkedId)
            }
        }
    }
    

    Basically we are checking if isChecked is false, then checking if all the buttons are unselected, if so, we will then select the button, which was recently unselected.