【问题标题】:Android MaterialButton Set Check in XML for DataBindingAndroid MaterialButton Set Check in XML for DataBinding
【发布时间】:2021-03-13 23:15:30
【问题描述】:

我在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" />

    ...

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

【问题讨论】:

  • 能不能换成app:checked看看
  • @Zain 它无法编译。

标签: android android-xml android-databinding android-binding-adapter materialbutton


【解决方案1】:

最后,我必须使用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

【讨论】:

    【解决方案2】:

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

    您也可以查看documentation

    【讨论】:

    • 感谢您的回答,但这是一种“硬代码”,不太适合我的情况。
    猜你喜欢
    • 2017-02-27
    • 2015-03-26
    • 2011-08-24
    • 2023-04-05
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多