问题简述:
在修改Button的背景颜色时,始终无法修改颜色为设置的颜色,且颜色始终为默认的蓝紫色。
<Button
android:id="@+id/btn_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/btn_1"
android:backgroundTint="@null"
android:textSize="20sp"
android:textColor="#FFFFFF"
android:background="#FF0011"></Button>
<Button
android:id="@+id/btn_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/btn_2"
android:textSize="20sp"
android:textColor="#FFFFFF"
android:backgroundTint="@null"
android:background="@drawable/bg_btn2"
android:layout_below="@id/btn_1"
android:layout_marginTop="20dp"></Button>
<Button
android:id="@+id/btn_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按钮3"
android:textSize="20sp"
android:backgroundTint="@null"
android:textColor="#FF9900"
android:background="@drawable/bg_btn3"
android:layout_below="@id/btn_2"
android:layout_marginTop="20dp"></Button>
<Button
android:id="@+id/btn_4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按钮4"
android:textSize="20sp"
android:backgroundTint="@null"
android:textColor="#FFFFFF"
android:background="@drawable/bg_btn4"
android:layout_below="@id/btn_3"
android:layout_marginTop="20dp"></Button>
上文中drawable/bg_btn等颜色为非默认蓝紫色。
实际模拟机效果(真机效果一样)如下:
问题解决:
博主的解决方法:
默认的颜色设置来自于res/values/themes.xml与夜间模式(应该是)下的res/values-night/themes.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.HelloWorld" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>
将(或你选择的其它主题)
<style name="Theme.HelloWorld" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
修改为(或其它能够实现非默认颜色的主题)
<style name="Theme.HelloWorld" parent="Theme.MaterialComponents.DayNight.DarkActionBar.Bridge">
即可解决问题,修改后的效果图如下:
当然,经过搜索,还得到了以下解决方法,虽然没有解决我的问题,但是希望能够帮到你:
1、给按钮增加一个属性app:backgroundTint="@null"
2、点击菜单中的 “baiFile” -> “Invalidate Caches / Restart”,然后点击对话框中的 “Invalidate and Restart”,清空 cache 并且重启。
3、更换旧版本(或许确实是版本问题)
4、将themes文件下的<style> 中的所有默认属性注释掉(亲测有效,或许这才是正确方法)
问题总结:
虽然不知道原理是什么,但是在搜索问题的时候很少人遇到这种问题,且遇到问题的多半是近期提问。总结来说应该是更新问题导致的,或者说因为我选择了空白项目导致使用了默认的themes。