如何设置Material Button Toggle Group中所有按钮的圆角半径?
当然可以调整内部按钮的圆角,你遇到的问题确实是因为MaterialButtonToggleGroup默认会修改子按钮的边角样式,只保留首尾按钮的外侧圆角。下面给你两种可行的解决方法:
方法一:用 shapeAppearanceOverlay 强制覆盖样式
通过自定义shapeAppearanceOverlay直接指定所有边角的圆角大小,同时绕过ToggleGroup的默认形状调整逻辑:
- 在
res/values/styles.xml里定义自定义形状样式:
<style name="CustomToggleButtonStyle" parent="Widget.MaterialComponents.Button.OutlinedButton"> <item name="shapeAppearanceOverlay">@style/ShapeAppearance.CustomToggleButton</item> <item name="strokeWidth">2dp</item> <item name="strokeColor">@color/your_stroke_color</item> </style> <style name="ShapeAppearance.CustomToggleButton" parent=""> <item name="cornerSize">16dp</item> <!-- 这里填你想要的圆角尺寸 --> </style>
- 在布局中给ToggleGroup设置单选/多选模式,同时给每个子MaterialButton应用上面的样式:
<com.google.android.material.button.MaterialButtonToggleGroup android:layout_width="wrap_content" android:layout_height="wrap_content" app:singleSelection="true"> <com.google.android.material.button.MaterialButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮1" style="@style/CustomToggleButtonStyle"/> <com.google.android.material.button.MaterialButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮2" style="@style/CustomToggleButtonStyle"/> <com.google.android.material.button.MaterialButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮3" style="@style/CustomToggleButtonStyle"/> </com.google.android.material.button.MaterialButtonToggleGroup>
方法二:代码动态设置边角
如果需要更灵活的控制,可在代码里给每个子按钮单独设置圆角:
val toggleGroup = findViewById<MaterialButtonToggleGroup>(R.id.your_toggle_group_id) val cornerRadius = resources.getDimensionPixelSize(R.dimen.corner_radius_16dp).toFloat() for (i in 0 until toggleGroup.childCount) { val button = toggleGroup.getChildAt(i) as MaterialButton button.shapeAppearanceModel = button.shapeAppearanceModel .toBuilder() .setAllCornerSizes(cornerRadius) .build() }
注意:如果是多选模式,ToggleGroup默认会让相邻按钮的内侧边角变直角,上面两种方法都能强制覆盖这个默认行为,实现全圆角效果。
内容的提问来源于stack exchange,提问作者Haeiny
相关产品推荐
相关产品推荐

