MaterialButtonToggleGroup中MaterialButton无法实现wrap_content问题求助
核心配置方案
无需更换视图,通过配置MaterialButtonToggleGroup和内部MaterialButton的属性即可实现需求:
1. 开启ToggleGroup换行支持
给MaterialButtonToggleGroup添加以下属性:
app:singleLine="false":解除单行限制,允许按钮自动换行app:allowSingleSelection="true":开启单选模式,简化切换逻辑app:selectionRequired="true"(可选):确保始终有一个按钮处于选中状态
2. 实现按钮换行+等高
给每个内部MaterialButton配置:
android:maxLines="2"(数值按需调整):允许文本换行显示android:layout_height="match_parent":让按钮高度匹配ToggleGroup,实现等高android:layout_width="0dp"+app:layout_weight="1":让按钮平分ToggleGroup宽度,保证布局均匀
3. 添加圆角效果
给MaterialButton添加:
app:cornerRadius="16dp"(数值按需调整):直接设置圆角- 可选:
app:cornerRadiusChecked:单独设置按钮选中状态下的圆角值,实现差异化样式
完整示例代码
<com.google.android.material.button.MaterialButtonToggleGroup android:layout_width="match_parent" android:layout_height="wrap_content" app:singleLine="false" app:allowSingleSelection="true" app:selectionRequired="true"> <com.google.android.material.button.MaterialButton android:id="@+id/btn_first" android:layout_width="0dp" android:layout_height="match_parent" app:layout_weight="1" android:text="较长的按钮文本内容,需要换行显示" android:maxLines="2" app:cornerRadius="16dp"/> <com.google.android.material.button.MaterialButton android:id="@+id/btn_second" android:layout_width="0dp" android:layout_height="match_parent" app:layout_weight="1" android:text="另一个需要换行显示的按钮文本" android:maxLines="2" app:cornerRadius="16dp"/> </com.google.android.material.button.MaterialButtonToggleGroup>
注意事项
- 确保Material Components库版本在
1.5.0及以上,早期版本不支持singleLine="false"属性 - 若按钮高度仍不一致,可给ToggleGroup设置固定高度(如
android:layout_height="60dp"),按钮设为match_parent强制等高 - 复杂样式需求可自定义MaterialButton的style,继承
Widget.MaterialComponents.Button修改状态属性
内容的提问来源于stack exchange,提问作者msc87
相关产品推荐
相关产品推荐

