自定义按钮颜色时如何统一设置按钮圆角半径?
嘿,这个场景我太熟悉了!你遇到的问题本质是:单独设置只含圆角的drawable作为背景时,它没有继承你在样式里定义的colorButtonNormal颜色,所以默认显示白色,覆盖了原有颜色。不用创建多个drawable文件,咱们只需要修改现有的primary_button.xml就能搞定~
核心解决方案:让Drawable继承主题颜色属性
直接在你的shape里添加一个<solid>标签,引用?attr/colorButtonNormal这个主题属性,这样drawable就会自动使用当前按钮样式中设置的colorButtonNormal颜色,同时保留统一的圆角设置。
修改后的primary_button.xml代码如下:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape> <corners android:radius="5dip"/> <!-- 关键:引用主题属性,继承样式里的colorButtonNormal颜色 --> <solid android:color="?attr/colorButtonNormal"/> </shape> </item> </selector>
这样修改后,你的BlackButton、GrayButton等子样式里的colorButtonNormal属性就会被这个drawable读取,按钮背景会自动变成对应的黑色、灰色,同时所有按钮都有统一的5dip圆角,完全不用创建多个drawable文件!
进阶:支持按钮状态(按下、禁用等)
如果你的按钮需要支持不同交互状态的颜色变化,还可以在selector里添加对应状态的item,引用主题里的状态属性,比如colorButtonPressed、colorButtonDisabled:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 按下状态 --> <item android:state_pressed="true"> <shape> <corners android:radius="5dip"/> <solid android:color="?attr/colorButtonPressed"/> </shape> </item> <!-- 禁用状态 --> <item android:state_enabled="false"> <shape> <corners android:radius="5dip"/> <solid android:color="?attr/colorButtonDisabled"/> </shape> </item> <!-- 默认状态 --> <item> <shape> <corners android:radius="5dip"/> <solid android:color="?attr/colorButtonNormal"/> </shape> </item> </selector>
这样按钮的各种状态颜色也能和你的主题保持一致,同时圆角始终统一。
确认样式设置
最后检查一下你的样式结构,确保PrimaryButton设置了android:background="@drawable/primary_button",子样式只需要覆盖colorButtonNormal和textColor,比如:
<style name="PrimaryButton" parent="Widget.AppCompat.Button"> <item name="android:layout_width">wrap_content</item> <item name="android:layout_height">wrap_content</item> <item name="android:fontWeight">600</item> <item name="android:textAllCaps">false</item> <item name="android:background">@drawable/primary_button</item> </style> <style name="BlackButton" parent="PrimaryButton"> <item name="android:textColor">#ffffff</item> <item name="colorButtonNormal">@color/black</item> </style> <style name="GrayButton" parent="PrimaryButton"> <item name="android:textColor">#ffffff</item> <item name="colorButtonNormal">@color/gray</item> </style>
这样就完美实现了统一圆角、保留原有颜色、无需多drawable文件的需求~
内容的提问来源于stack exchange,提问作者Nikita Goncharuk

