侧边栏壁纸
博主头像
Stars-One的杂货小窝博主等级

所有的创作都是有价值的

  • 累计撰写 257 篇文章
  • 累计创建 46 个标签
  • 累计收到 27 条评论

目 录CONTENT

文章目录

Android MaterialButtonToggleGroup使用

Stars-one
2023-12-13 / 0 评论 / 0 点赞 / 128 阅读 / 3813 字

觉得单选框不好看,发现了一个Material里的单选按钮组,感觉UI还不错,记下使用

使用

效果:

使用前,得看看是否有material的依赖,如

implementation 'com.google.android.material:material:1.4.0'

PS: 一般新的Android项目创建都是默认带上material组件依赖的

<com.google.android.material.button.MaterialButtonToggleGroup
    android:id="@+id/toggleGroup"
    app:singleSelection="true"
    app:checkedButton="@id/mbLanzou"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="wrap_content">
    <com.google.android.material.button.MaterialButton
        android:id="@+id/mbLanzou"
        android:layout_weight="1"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="蓝奏云解析"/>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/mbLanzouYx"
        android:layout_weight="1"
        android:layout_width="0dp"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"
        android:layout_height="wrap_content"
        android:text="蓝奏云优享版解析"/>
</com.google.android.material.button.MaterialButtonToggleGroup>
  • checkedButton 默认选中按钮id
  • singleSelection 是否单选
  • orientation 元素排列方向
  • selectionRequired 是否必须要选中

当 selectionRequired 属性设置为 true 时,用户必须选择组中的至少一个按钮。如果用户尝试取消选择所有按钮,MaterialButtonToggleGroup 将自动选择第一个按钮。

当 selectionRequired 属性设置为 false 时,用户可以不选择任何按钮,也可以选择其中的一个按钮。

感觉selectionRequired 是应该是结合多选来使用

MaterialButtonToggleGroup本质上和线性布局LinearLayout差不多,里面的元素也可以使layout_weight权重

关于代码示例:

//获取当前选中的按钮id
toggleGroup.checkedButtonId

//获取按钮id列表
toggleGroup.checkedButtonIds

//监听按钮选中
toggleGroup.addOnButtonCheckedListener { group, checkedId, isChecked ->
    //checkedId为选中按钮id
    
    if (checkedId == R.id.mbLanzou) {
       //判断选中按钮之后逻辑
    } else {
        
    }
}

//选中某个按钮
toggleGroup.check(R.id.mbLanzou)

参考

0

评论区