Android按钮背景颜色在xml上没有改变
- 安卓斯蒂迪奥 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>
在此处输入图片说明
我认为它可能工作正常,但它仍然是紫色:(
回答
如果您使用的是 Android Studio 4.1.1,您可能正在使用 Theme.MaterialComponents 检查您的 themes.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 中的主题来更改所有项目的主题,如下所示:
我希望这是有用的。