Android Button背景继承colorPrimary,自定义背景失效如何解决?
这个问题我之前也碰到过!因为你用的是Google Material Design库的Button(在Material主题下,系统会自动把Button替换为MaterialButton),它默认会用主题的colorPrimary作为背景着色(通过backgroundTint属性),就算你设置了android:background,这个着色层也会覆盖你的自定义背景,导致看起来还是colorPrimary的颜色。
下面给你几个可行的解决方案:
方法1:直接在布局中禁用backgroundTint
给你的Button添加app:backgroundTint="@null"属性,这样就能取消默认的背景着色,让自定义drawable生效。记得要确保布局根节点已经声明了app命名空间(xmlns:app="http://schemas.android.com/apk/res-auto")。
修改后的布局代码:
<Button android:id="@+id/btn_teacher" style="@style/normalText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="@dimen/_16sdp" android:background="@drawable/btn_rounded_stroke" app:backgroundTint="@null" android:text="@string/txt_teacher" />
方法2:自定义Style统一处理(适合多个按钮)
如果有多个不同颜色的按钮,推荐创建一个通用的Style,把backgroundTint="@null"放到Style里,这样所有按钮只需要引用这个Style就能生效,不用重复写属性:
首先在styles.xml中添加自定义Style:
<style name="CustomButtonBase" parent="Widget.MaterialComponents.Button"> <!-- 禁用默认背景着色 --> <item name="backgroundTint">@null</item> <!-- 可以在这里添加其他通用属性,比如文字样式等 --> </style>
然后让你的normalTextStyle继承这个自定义Style(或者直接让按钮引用CustomButtonBase):
<style name="normalText" parent="CustomButtonBase"> <!-- 你的normalText原有属性 --> </style>
这样所有使用normalTextStyle的Button都会自动禁用背景着色,自定义背景就能正常显示了。
为什么会出现这个问题?
MaterialButton的设计逻辑是通过backgroundTint来控制背景颜色,默认情况下它会读取主题中的colorPrimary作为着色值,这是Material Design组件的默认行为。所以如果你想使用自己的自定义背景drawable,必须先禁用这个默认的着色层,否则你的drawable会被着色覆盖,看起来还是colorPrimary的颜色。
内容的提问来源于stack exchange,提问作者Fath.Saif

