我在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
就是不起作用,我可以在Activity
或Fragment
中使用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