You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中XML按钮设为黑色却显示紫色的问题

按钮设置黑色背景却显示紫色的解决方法

这是因为你当前使用的是Material Design主题(比如Theme.MaterialComponents.*),这类主题下的Button控件会默认应用主题的colorPrimary作为背景着色(tint),直接覆盖了你设置的android:background属性,而紫色通常是默认的colorPrimary颜色。

以下是几种可行的解决办法:

  • 改用AppCompatButton
    将布局中的<Button>标签替换为<androidx.appcompat.widget.AppCompatButton>,这个控件不会默认应用Material主题的背景着色,设置的android:background会正常生效:

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/bac"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#000"
        android:text="AC"
        android:textColor="#33ccff"
        android:textSize="23sp" />
    
  • 禁用背景着色
    在原Button标签中添加app:backgroundTint="@null",同时确保根布局中引入了app命名空间:

    1. 根布局添加命名空间:
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          ...>
      
    2. 修改Button属性:
      <Button
          android:id="@+id/bac"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:layout_weight="1"
          android:background="#000"
          app:backgroundTint="@null"
          android:text="AC"
          android:textColor="#33ccff"
          android:textSize="23sp" />
      
  • 自定义无着色的Button样式
    在res/values/styles.xml中定义一个样式:

    <style name="NoTintButton" parent="Widget.MaterialComponents.Button">
        <item name="backgroundTint">@null</item>
    </style>
    

    然后给Button设置该样式:

    <Button
        android:id="@+id/bac"
        style="@style/NoTintButton"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#000"
        android:text="AC"
        android:textColor="#33ccff"
        android:textSize="23sp" />
    

内容的提问来源于stack exchange,提问作者AlecW123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:55:23