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?
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