Android Studio覆盖自定义按钮Drawable样式问题求助
解决自定义透明边框按钮被主题颜色覆盖的问题
1. 关掉Button的背景着色(backgroundTint)
Material Components的Button默认会启用backgroundTint,这玩意儿优先级比background高,直接把你的自定义Drawable给覆盖了。最简单的办法就是在按钮XML里直接把它设为null:
<Button android:id="@+id/custom_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="自定义按钮" app:background="@drawable/button_custom" app:backgroundTint="@null" /> <!-- 关键:把背景着色清空 -->
要是不想每个按钮都写,就全局配置主题:
在styles.xml的AppTheme里加一行:
<item name="materialButtonStyle">@style/CustomMaterialButton</item>
然后定义这个自定义样式:
<style name="CustomMaterialButton" parent="Widget.MaterialComponents.Button"> <item name="backgroundTint">@null</item> </style>
2. 检查你的自定义Drawable写对了没
确保button_custom.xml是正经的透明背景加白色边框,用shape写的话应该是这样:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!-- 透明背景必须明确设置 --> <solid android:color="@android:color/transparent" /> <!-- 白色边框 --> <stroke android:width="2dp" android:color="@android:color/white" /> <!-- 想要圆角就加这个,不用可以删掉 --> <corners android:radius="8dp" /> </shape>
之前要是没明确设solid为透明,就会继承主题的背景色,自然会变成红色。
3. 换个Button控件试试
如果你用的是MaterialButton或者AppCompatButton,它们的背景逻辑和原生Button不一样。要是不需要Material那些花里胡哨的特性,直接改用原生Button就行,注意用android:background而不是app:background:
<Button android:id="@+id/custom_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="自定义按钮" android:background="@drawable/button_custom" />
4. 清缓存重启AS
有时候AS的缓存抽风,导致显示不正常。点File -> Invalidate Caches... -> Invalidate and Restart,重启后重新构建项目,说不定就好了。
内容的提问来源于stack exchange,提问作者AThomas98
相关产品推荐
相关产品推荐

