Material Button Toggle Group single selection

前端 未结 4 1985
抹茶落季
抹茶落季 2021-02-19 04:55

How can I force a MaterialButtonToggleGroup to act like a RadioGroup as in having at least one selected item always? Setting setSingleSelection(true)

相关标签:
4条回答
  • 2021-02-19 05:24

    Override the toggle() method of the MaterialButton class and use it instead of MaterialButton

    import android.content.Context
    import android.util.AttributeSet
    import com.google.android.material.button.MaterialButton
    
    class CustomMaterialToggleButton : MaterialButton {
    
        constructor(context: Context) : super(context)
    
        constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    
        constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    
        override fun toggle() {
            if (!isChecked) {
                super.toggle()
            }
        }
    }
    

    This will make sure that already checked button is not unchecked on single selection.

    UPDATE :

    app:selectionRequired="true" attribute is available as of version 1.2.0

    0 讨论(0)
  • 2021-02-19 05:35

    As of 1.2.0-alpha03 you can simply use the selectionRequired option:

    <com.google.android.material.button.MaterialButtonToggleGroup
        android:id="@+id/toggle_button_group"
        app:singleSelection="true"
        app:selectionRequired="true">
    
    </com.google.android.material.button.MaterialButtonToggleGroup>
    
    0 讨论(0)
  • 2021-02-19 05:38

    If you really want to do this, you can go about it this way in Kotlin.

    toggle_group.forEach { button ->
          button.setOnClickListener { (button as MaterialButton).isChecked = true }
    }
    

    This will prevent second click unchecking.

    0 讨论(0)
  • 2021-02-19 05:51

    Now you can achieve it using the app:selectionRequired attribute.
    Something like:

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

    Also you can programmatically use the method setSelectionRequired:

    buttonGroup.setSelectionRequired(true);
    

    Please note that this attribute requires a minimum of version 1.2.0-alpha03

    0 讨论(0)
提交回复
热议问题