Android 中解决 Button 按钮背景色设置无效的问题

1、问题描述

  • 在布局文件中有两个 Button 按钮,为每个按钮设置不同的背景色,但是显示出来的效果都是紫色的,跟设置的颜色不同,布局文件如下所示:
kotlin 复制代码
	<Button
           android:id="@+id/button_cancel"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textSize="@dimen/sp_30"
           android:textColor="@color/white"
           android:text="@string/cancel"
           android:background="@color/blue"
           app:layout_constraintTop_toTopOf="parent"
           app:layout_constraintLeft_toLeftOf="parent">

       <Button
           android:id="@+id/button_confirm"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textSize="@dimen/sp_30"
           android:textColor="@color/white"
           android:text="@string/confirm"
           android:background="@color/red"
           app:layout_constraintTop_toTopOf="@+id/button_cancel"
           app:layout_constraintLeft_toRightOf="@+id/button_cancel"
           android:layout_marginStart="@dimen/dp_50"/>
  • 正常效果应该是一个显示蓝色,一个显示红色,但是实际效果是两个都显示紫色,如下所示:

2、原因分析

  • 这种现象是由于程序中设置了新版本主题,而新版本主题会导致按钮颜色显示异常。
kotlin 复制代码
    <style name="MyTheme.FullScreen" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
    </style>
  • 这里用了 Material 新版本主题 Theme.MaterialComponents.DayNight.NoActionBar。

3、解决方法

  • 通过修改主题可以解决该问题,修改 app/res/values 目录下的 themes.xml 文件,将父主题更改为 Theme.MaterialComponents.DayNight.NoActionBar.Bridge,成功解决了所有按钮颜色统一显示为紫色的问题。
kotlin 复制代码
    <style name="MyTheme.FullScreen" parent="Theme.MaterialComponents.DayNight.NoActionBar.Bridge">
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
    </style>
  • 显示效果

4、两个主题区别

  • Theme.MaterialComponents.DayNight.NoActionBar
    这是一个标准的 Material Components 主题,支持日夜模式切换(DayNight),并且不包含 ActionBar。适用于需要完全采用 Material Components 设计语言的应用程序,且不需要 ActionBar 的场景。
  • Theme.MaterialComponents.DayNight.NoActionBar.Bridge
    这是一个过渡主题,用于在迁移到 Material Components 时,保持与旧主题的兼容性。适用于从旧的主题(如 Theme.AppCompat)迁移到 Material Components 主题时,但又不想立即完全替换所有主题属性,可以使用这个桥接主题。
相关推荐
程序员码歌1 小时前
短思考第263天,每天复盘10分钟,胜过盲目努力一整年
android·前端·后端
安卓兼职framework应用工程师1 小时前
Android 10.0 按键智能机按键连续响两次的异常处理
android·audio·audioservice·按键音·按键声音
studyForMokey2 小时前
【Android 项目】个人学习demo随笔
android
吃喝不愁霸王餐APP开发者2 小时前
利用责任链模式解耦多平台(美团/饿了么)霸王餐接口的适配逻辑
android·责任链模式
百***78752 小时前
Step-Audio-2 轻量化接入全流程详解
android·java·gpt·php·llama
yangpipi-4 小时前
《C++并发编程实战》第5章 C++内存模型和原子操作
android·java·c++
云水木石6 小时前
Android 的下一个战场:Windows 应用与游戏?
android·windows·游戏
雨声不在7 小时前
Android文字渐变的实现
android·textview
GoldenPlayer7 小时前
KTS语法
android
GoldenPlayer7 小时前
后台服务Service销毁逻辑+单例造成的内存泄露
android