【问题标题】:Android Button background color not changing on xmlAndroid Button背景颜色在xml上没有改变
【发布时间】:2021-04-05 05:00:11
【问题描述】:
  • Android Stidio 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 xml android-layout


【解决方案1】:

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

所以你必须使用这个属性

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 中的主题来更改所有项目的主题,如下所示:

我希望这是有用的。

【讨论】:

  • 它工作,但我真的不需要 backgroundTint 选项。有什么办法只使用背景?
  • 如果您使用的是 android studio 4.1.1,您可能使用 Theme.MaterialComponents “检查项目中的themes.xml”如果您使用背景属性,它将使用默认颜色。阅读本文档material.io/components/buttons
  • 谢谢你的好答案,我认为使用不同类型的主题会更好。或降级 Android Studio 版本 :(
【解决方案2】:

可能是 Android Studio 正在向您显示 xml 的缓存视图。尝试根据您的图像从上面选择 Custom 的位置更改模拟器。如果它没有更新颜色,请尝试 Invalidate Cache and Restart 你的 Android Studio

【讨论】:

  • 感谢答案:D,但它仍然无法正常工作...... :(
  • 您的主题是 Theme.MaterialComponents 还是 Theme.AppCompat?尝试让你的风格Theme.MaterialComponents
【解决方案3】:

在你的 java 代码中使用它。

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

【讨论】:

    【解决方案4】:

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

    android studio 4.1.1 中截至 2021 年 2 月 4 日的最新版本如下

    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'
    

    【讨论】:

      猜你喜欢
      • 2021-04-08
      • 2015-10-29
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 2012-03-20
      相关资源
      最近更新 更多