Android MaterialButtonToggleGroup使用
  fXCoSNADUqrl 2023年12月14日 13 1

原文地址: Android MaterialButtonToggleGroup使用 - Stars-One的杂货小窝

觉得单选框不好看,发现了一个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)

参考

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月14日 0

google pwa

亲亲,你好啊,我是刚才发布了google pwa 免费上架海外APP永久包服务的,您这边想要免费上架APP到google可以联系我咨询哈,谢谢哦,我的TG沟通入口是这个:https://t.me/ROIBestBot?start=9240264518917495 期待与您进一步沟通啦。

2024-04-18 15:33:28      回复

推荐阅读
  co6JretT03bl   2024年03月29日   30   0   0 Android开发
  co6JretT03bl   2024年03月29日   22   0   0 Android开发
  co6JretT03bl   2024年03月22日   34   0   0 Android开发
  co6JretT03bl   2024年03月19日   25   0   0 Android开发
fXCoSNADUqrl