Android MaterialComponents主题下Button设置background无效

问题描述

使用的主题代码如下图:

    <!-- 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是无效的

方法2:修改主题,添加Bridge结尾的主题
如将

Theme.MaterialComponents.DayNight.DarkActionBar

改为:

Theme.MaterialComponents.DayNight.DarkActionBar.Bridge

使用这个方法可以让Button使用background属性设置背景颜色有效。

方法3: 更换api使用backgroundTint方法
使用这个api时Button的backgroundTint会生效,也可达到替换背景的效果。


实践总结
下面总结一下在MaterialComponents主题和以Bridge结尾的主题下Button、androidx.appcompat.widget.AppCompatButton、android.widget.Button、MaterialButton在xml中使用不同的api设置背景颜色和在Java中修改背景颜色的具体变化是否修改有效。

1、MaterialComponents主题下
在Theme.MaterialComponents.DayNight.DarkActionBar主题下。

在这里插入图片描述

结果发现,在 MaterialComponents 主题下 Button和MaterialButton设置背景颜色的效果一样,android.widget.Button 和 AppCompatButton设置背景颜色的效果一样。

android.widget.Button 和 AppCompatButton在xml布局中两种设置背景颜色的方法都能成功,在Java中修改背景颜色时,只要不在xml布局中同时使用backgroundTint属性,也都可以设置成功

2、以Bridge结尾的主题下
在Theme.MaterialComponents.DayNight.NoActionBar.Bridge主题下
在这里插入图片描述

其中:

xml空:表示xml中不使用 background 和 backgroundTint 设置背景颜色的前提下

xml空|background:表示 xml中不使用 background 和 backgroundTint 设置背景颜色或者 在xml中使用了background设置背景颜色的前提下。

xml空|backgroundTint:表示 xml中不使用 background 和 backgroundTint 设置背景颜色 或者 在xml中使用了backgroundTint设置背景颜色的前提下。

有效/无效:表示 xml中不使用 background 和 backgroundTint 设置背景颜色 或者 在xml中使用了background或backgroundTint设置背景颜色的前提下都有效/无效。

总结发现:Button、androidx.appcompat.widget.AppCompatButton、android.widget.Button在xml中设置背景颜色,无论使用那个api都能设置成功,在Java中设置背景颜色时只要保证不同时在xml布局中使用backgroundTint设置背景颜色就可以设置成功。
MaterialButton在xml中只能使用backgroundTint设置成功,在Java中只有使用setBackgroundColor()并且不能同时在xml布局中使用background属性时才能设置成功。

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值