【问题标题】:background color of Android Button is not changingAndroid Button的背景颜色没有改变
【发布时间】:2021-04-08 05:33:53
【问题描述】:
按钮的背景颜色不会改变。
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@color/purple_500">
<Button
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:background="@color/white"/>
</androidx.constraintlayout.widget.ConstraintLayout>
这是布局和蓝图的样子:
【问题讨论】:
标签:
java
android
button
background-color
【解决方案2】:
用app:backgroundTint代替android:background。
这将使您的代码如下所示:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@color/purple_500">
<Button
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:backgroundTint="@color/white"/>
</androidx.constraintlayout.widget.ConstraintLayout>
【解决方案3】:
另一种方式是 ThemeOverlay,你可以像这样制作 ThemeOverlay:
<style name="ThemeOverlay.Button.Red" parent="MaterialButtonStyle">
<item name="colorOnPrimary">@color/white</item>
<item name="colorPrimary">@color/red</item>
</style>
然后
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/purple_500">
<com.google.android.material.button.MaterialButton
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:theme="@style/ThemeOverlay.Button.Red"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
colorPrimary=按钮的背景
colorOnPrimary= 按钮的 textColor