android按钮的背景色不变

xj3cbfub  于 2021-06-29  发布在  Java
关注(0)|答案(3)|浏览(594)

按钮的背景色不会改变。
代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.constraintlayout.widget.ConstraintLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. xmlns:app="http://schemas.android.com/apk/res-auto"
  7. android:background="@color/purple_500">
  8. <Button
  9. android:layout_width="40dp"
  10. android:layout_height="40dp"
  11. android:layout_margin="5dp"
  12. app:layout_constraintTop_toTopOf="parent"
  13. app:layout_constraintLeft_toLeftOf="parent"
  14. android:background="@color/white"/>
  15. </androidx.constraintlayout.widget.ConstraintLayout>

这就是布局和蓝图的外观:

ocebsuys

ocebsuys1#

我不能添加简单的评论抱歉,所以这里是我的解决方案;可以使用backgroundtint属性而不是background,也可以为按钮添加自定义样式https://stackoverflow.com/a/31858629/13447094

efzxgjgh

efzxgjgh2#

而不是 android:background 使用 app:backgroundTint .
这将使您的代码如下所示:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.constraintlayout.widget.ConstraintLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. xmlns:app="http://schemas.android.com/apk/res-auto"
  7. android:background="@color/purple_500">
  8. <Button
  9. android:layout_width="40dp"
  10. android:layout_height="40dp"
  11. android:layout_margin="5dp"
  12. app:layout_constraintTop_toTopOf="parent"
  13. app:layout_constraintLeft_toLeftOf="parent"
  14. app:backgroundTint="@color/white"/>
  15. </androidx.constraintlayout.widget.ConstraintLayout>
展开查看全部
rbpvctlc

rbpvctlc3#

另一种方法是themeoverlay,你可以这样做themeoverlay:

  1. <style name="ThemeOverlay.Button.Red" parent="MaterialButtonStyle">
  2. <item name="colorOnPrimary">@color/white</item>
  3. <item name="colorPrimary">@color/red</item>
  4. </style>

然后

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.constraintlayout.widget.ConstraintLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:background="@color/purple_500">
  8. <com.google.android.material.button.MaterialButton
  9. android:layout_width="40dp"
  10. android:layout_height="40dp"
  11. android:layout_margin="5dp"
  12. android:theme="@style/ThemeOverlay.Button.Red"
  13. app:layout_constraintLeft_toLeftOf="parent"
  14. app:layout_constraintTop_toTopOf="parent" />
  15. </androidx.constraintlayout.widget.ConstraintLayout>

colorprimary=按钮的背景
coloronprimary=text按钮的颜色

展开查看全部

相关问题