Android MaterialButton为DataBinding设置签入XML



我在MaterialButtonToggleGroup:中使用MaterialButton

<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" />
...

配置android:checked就是不起作用,我可以在ActivityFragment中使用setCheck(),但要使用DataBniding,我必须使用XML属性。有什么帮助吗?

要将MaterialButton的初始状态默认设置为一组按钮中的选中按钮,您可以通过在MaterialButtonToggleGroup中引用app:checkedButton中的按钮id来执行此操作

所以,在你的代码中:

<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" />
...

您也可以查看文档。

最后,我必须使用BindingAdapter函数来实现此功能。

1.创建BindingAdapter函数:

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

2.应用于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

最新更新