You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让MaterialButtonToggleGroup内的按钮均等宽填充整个组件宽度

解决方法

MaterialButtonToggleGroup本质是继承自水平LinearLayout的容器,无需嵌套额外布局,直接用权重属性即可实现子按钮均分宽度的效果,修改方式如下:

  • 所有子Button的android:layout_width属性从wrap_content改为0dp
  • 给每个子Button新增android:layout_weight="1"属性

修改后的完整代码:

<com.google.android.material.button.MaterialButtonToggleGroup
    android:id="@+id/button_group"
    android:layout_width="380dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="15dp"
    android:layout_marginEnd="15dp"
    android:gravity="center">

    <Button
        android:id="@+id/button_one"
        style="?attr/materialButtonOutlinedStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Bachelor" />

    <Button
        android:id="@+id/button_center"
        style="?attr/materialButtonOutlinedStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Master" />

    <Button
        android:id="@+id/button_three"
        style="?attr/materialButtonOutlinedStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Doctoral" />

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

如果后续需要调整按钮数量,只要每个新增的按钮都按上述规则设置layout_width和layout_weight属性,就能自动实现均等宽度拉伸、占满容器总宽度的效果。

内容的提问来源于stack exchange,提问作者Hexley21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:09:02