Android MaterialComponents主题下Button设置background无效

473 阅读1分钟

问题描述

使用的主题代码如下图:

<!-- Base application theme. -->
<style name="Base.Theme.MyApplication" parent="Theme.Material3.DayNight.NoActionBar">
    <!-- Customize your light theme here. -->
    <!-- <item name="colorPrimary">@color/my_light_primary</item> -->
</style>

<style name="Theme.MyApplication" parent="Base.Theme.MyApplication" />
</resources>

布局中只有一个Button,代码如下:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="按钮"
    android:background="@color/blue"/>

最终运行出来的结果应该是蓝色的按钮,但实际上按钮还是主题色(即主题代码中”colorPrimary”属性的值)。

原因 MaterialComponents主题下所有Button都是Material类型的Button,默认使用主题色。

解决 解决方式有如下几种:

方法1: 使用android.widget.Button代替Button 将

<Button
    android:id="@+id/btn_1"

改为:

<android.widget.Button
    android:id="@+id/btn_1"

使用这个方法可以让Button使用background属性设置背景颜色有效。 注意:此时android.widget.Button的backgroundTint是无效的