首页 > 解决方案 > 自 Android Studio 4.1 起,Android Background Drawable 在按钮中不起作用

问题描述

我发现自 Android Studio 4.1 以来,我无法Button通过在其上设置颜色来更改 a 的背景颜色android:background,只是没有效果。自定义Drawable也不起作用。

我的背景Drawable

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <stroke
        android:width="1.5dp"
        android:color="@android:color/black" />

    <solid
        android:color="@android:color/white" />

    <corners
        android:radius="8dp" />

</shape>

我的Button

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add To Cart"
    android:background="@drawable/background3"/>

结果:

在此处输入图像描述

标签: androidmaterial-designandroid-drawableandroid-buttonandroid-styles

解决方案


Android Studio 4.1 新建项目向导,对于它的许多模板,让项目使用 Android 库的 Material Components。并且,它将默认主题设置为基于Theme.MaterialComponents.DayNight.DarkActionBar.

这样做的副作用是<Button>布局中的任何元素都会变成MaterialButton小部件,而不是常规的Button小部件。MaterialButton忽略android:background

如果您只想更改颜色,请使用android:backgroundTint或更改colorPrimary主题中的属性。

如果您想要一个具有自定义背景的按钮,并且您的主题设置为使用Theme.MaterialComponents,您可以将布局中的 XML 元素切换为<android.widget.Button>而不是<Button>. 这应该会导致 Android 的 Material 组件忽略该元素,并且您可以针对 XML 属性正常操作此按钮。


推荐阅读