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

Android Studio按钮背景颜色修改异常求助:设置后显示紫色

Android Button背景颜色不生效问题解决方法

你遇到的问题是因为Android 5.0(API 21)及以上版本,默认的Button采用了Material Design风格,系统会忽略android:background属性,转而使用主题中的colorPrimary等配色渲染按钮,导致设置的背景色不生效。以下是几种直接有效的解决办法:

方法一:使用android:backgroundTint替代android:background

Material Design风格的Button用backgroundTint控制背景色,直接替换属性即可:

<Button
    android:id="@+id/id_button"
    android:text="xem thời gian"
    android:backgroundTint="@android:color/black"
    android:textColor="@android:color/white"
    android:layout_centerHorizontal="true"
    android:layout_width="380dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"/>

方法二:切换到AppCompat风格按钮

给Button指定AppCompat样式,就能正常使用android:background属性:

<Button
    android:id="@+id/id_button"
    android:text="xem thời gian"
    style="@style/Widget.AppCompat.Button"
    android:background="@android:color/black"
    android:textColor="@android:color/white"
    android:layout_centerHorizontal="true"
    android:layout_width="380dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"/>

方法三:自定义背景Drawable(适合需要特殊样式的场景)

在res/drawable目录下创建button_black_bg.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/black"/>
    <!-- 可选:添加圆角、边框等样式 -->
    <corners android:radius="4dp"/>
</shape>

然后在Button中引用该Drawable:

<Button
    android:id="@+id/id_button"
    android:text="xem thời gian"
    android:background="@drawable/button_black_bg"
    android:textColor="@android:color/white"
    android:layout_centerHorizontal="true"
    android:layout_width="380dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"/>

内容的提问来源于stack exchange,提问作者Nguyễn Anh Việt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:45:30