当前位置: 首页 > ds >正文

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

1、问题描述

  • 在布局文件中有两个 Button 按钮,为每个按钮设置不同的背景色,但是显示出来的效果都是紫色的,跟设置的颜色不同,布局文件如下所示:
	<Buttonandroid: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"><Buttonandroid: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、原因分析

  • 这种现象是由于程序中设置了新版本主题,而新版本主题会导致按钮颜色显示异常。
    <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,成功解决了所有按钮颜色统一显示为紫色的问题。
    <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 主题时,但又不想立即完全替换所有主题属性,可以使用这个桥接主题。
http://www.xdnf.cn/news/17427.html

相关文章:

  • Numpy科学计算与数据分析:Numpy广播机制入门与实践
  • conda pip uv与pixi
  • react的form.resetFields()
  • 论文阅读:User Behavior Simulation with Large Language Model-based Agents
  • 五十五、【Linux系统nginx服务】nginx安装、用户认证、https实现
  • MySQL 配置性能优化赛:核心策略与实战技巧
  • HTML5 Web Workers 深度剖析:助力网页性能飞速提升
  • dmctlcvt工具介绍数据文件路径变化后如何拉起数据库
  • 边缘算力×AI应用:如何在2025年实现爆发式增长
  • HTML已死,HTML万岁——重新思考DOM的底层设计理念
  • 用LaTeX优化FPGA开发:结合符号计算与Vivado工具链
  • 《C语言》函数练习题--1
  • 通过CNN、LSTM、CNN-LSTM及SSA-CNN-LSTM模型对数据进行预测,并进行全面的性能对比与可视化分析
  • 前端开发工具大全
  • day069-Jenkins基础使用与参数化构建
  • 【论文阅读】基于元模型的体系知识图谱构建
  • DataEase官方出品丨SQLBot:基于大模型和RAG的智能问数系统
  • C++高频知识点(十五)
  • 浅谈欧拉函数与素数筛法思想
  • Flink的运行模式
  • [网格图DP]3363. 最多可收集的水果数目
  • 水库大坝安全监测系统主要概述
  • 函数、方法和计算属性
  • P1037 [NOIP 2002 普及组] 产生数
  • 【论坛系统自动化功能测试报告】
  • 【深度学习机器学习】构建情绪对话模型:从数据到部署的完整实践
  • 如何使用 pnpm创建Vue 3 项目
  • 神策埋点是什么
  • 7. 什么是事件委托
  • 数据结构学习之二叉树