如何让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
相关产品推荐
相关产品推荐

