如何使 Android 中的 material 切换按钮表现得像 Switch?

How to make material toggle button in Android to behave like Switch?

我正在使用以下 material 设计库

implementation "com.google.android.material:material:1.2.0-alpha01"

这就是我实现 Material 切换按钮

的方式
<com.google.android.material.button.MaterialButtonToggleGroup
    id="@+id/toggleBtnGroup"
    app:singleSelection="true"
    android:id="@+id/toggle_button_group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:checkedButton="@+id/leftAlign">

    <com.google.android.material.button.MaterialButton
        id="@+id/leftAlign"
        style="?attr/materialButtonOutlinedStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Left"/>
    <com.google.android.material.button.MaterialButton
        id="@+id/centerAlign"
        style="?attr/materialButtonOutlinedStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Center"/>
    <com.google.android.material.button.MaterialButton
        id="@+id/rightAlign"
        style="?attr/materialButtonOutlinedStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Right"/>

</com.google.android.material.button.MaterialButtonToggleGroup>

现在,正如我 select 其他按钮一样,一次只有 1 个按钮被 select 编辑,我如何确保如果用户 select 是 selected 按钮,它不会被取消selected。所以本质上,我希望至少有一个按钮在特定时间被 selected。

如何做到这一点?

要实现这一点,请执行以下操作:-

//We are adding a button checked listener to the toggle group
toggleBtnGroup.addOnButtonCheckedListener { group, checkedId, isChecked ->
    if (isChecked){
        //Do something
    } else {
        //Something is unchecked, we need to make sure that all the buttons are not un-selected
        if(-1 == group.checkedButtonId){
            //All buttons are unselected
            //So now we will select the button which was unselected right now
            group.check(checkedId)
        }
    }
}

基本上我们检查 isChecked 是否为 false,然后检查所有按钮是否未selected,如果是,我们将 select 最近未[=15] 的按钮=]ed.

最近,我遇到了同样的问题,当我点击按钮两次时,它取消选中了按钮。我通过 .

MaterialButton class 的 Override toggle() 方法解决了这个问题

您可以使用 app:selectionRequired 属性。
类似于:

    <com.google.android.material.button.MaterialButtonToggleGroup
        app:singleSelection="true"
        app:selectionRequired="true"
        app:checkedButton="@id/..."
        ..>

你也可以使用方法setSelectionRequired:

buttonGroup.setSelectionRequired(true);

此属性需要 最低版本1.2.0-alpha03