Android MaterialButton Set Check in XML for DataBinding

1.9k views Asked by At

I'm using MaterialButton within MaterialButtonToggleGroup:

<com.google.android.material.button.MaterialButtonToggleGroup
    android:id="@+id/majors_toggleGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/cs_button"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"                //doesn't work
        android:text="CS" />

    ...

The arrtribute android:checked just doesn't work, I can use setCheck() in Activity or Fragment, but for using DataBniding I have to use the XML attribute. Any help?

2

There are 2 answers

0
Sam Chen On BEST ANSWER

Finally, I have to use BindingAdapter function to achieve this functionality.

1. Create BindingAdapter Function:

object DataBindingUtil {
    @BindingAdapter("checkedIndexes")        //custom attribute
    @JvmStatic
    fun setChecked(toggleGroup: MaterialButtonToggleGroup, checkedIndexes: List<Int>) {
        checkedIndexes.forEach {
            (toggleGroup.getChildAt(it) as MaterialButton).isChecked = true
        }
    }
}

2. Apply to MaterialButtonToggleGroup:

<com.google.android.material.button.MaterialButtonToggleGroup
    android:id="@+id/majors_toggleGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    app:checkedIndexes="@{viewModel.majorIndexes}">    //here, multi-selection for now
1
Zain On

To set your initial state of MaterialButton as the checked button by default in a group of buttons, you can do that by referencing the button id in app:checkedButton in the MaterialButtonToggleGroup

So, In your code:

<com.google.android.material.button.MaterialButtonToggleGroup
    android:id="@+id/majors_toggleGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:checkedButton="@+id/cs_button" 
    android:layout_marginTop="8dp">

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

    ...

You may also check documentation.