Android MaterialComponents主题下Button设置background无效

问题描述

使用的主题代码如下图:

    
    
        
        <!-- @color/my_light_primary -->
    

    

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

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

原因

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

解决

解决方式有如下几种:

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

<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属性时才能设置成功。

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/08c034cc00.html