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属性时才能设置成功。
相关链接
评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。
发表评论