Android按钮背景颜色在xml上没有改变

问题描述

  • Android Stdio 4.1.1
    • SDK 29 (Android 10)

我尝试更改 xml 上的按钮背景颜色,但没有更改。

这是我的代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"/>

</LinearLayout>

enter image description here

我认为它可能工作正常,但它仍然是紫色:(

解决方法

如果您使用的是 Android Studio 4.1.1,您可能正在使用 Theme.MaterialComponents 检查你的 themes.xml 文件

enter image description here

所以你必须使用这个属性

android:backgroundTint="#ff0000"

阅读此文档了解更多信息:

https://material.io/components/buttons

如果您坚持使用 android:background,您可以像这样更改按钮 xml 代码以使用 appcompat 强制它:

<androidx.appcompat.widget.AppCompatButton
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ff0000"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

或者您可以通过像这样更改 themes.xml 中的主题来更改所有项目的主题:

enter image description here

我希望这是有用的。

,

可能是 Android Studio 向您展示了 xml 的缓存视图。尝试从上方根据您的图像选择自定义更改模拟器。如果它没有更新颜色,请尝试使缓存无效并重新启动您的 Android Studio

,

在您的 Java 代码中使用它。

button1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#ff0000")));
,

确保 build.gradle(app) 文件中的所有应用依赖项都是最新的。

截至 2021 年 2 月 4 日,android studio 4.1.1 的最新情况如下

implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...