自 Android Studio 4.1 以来,Android 背景可绘制对象在按钮中不起作用

新手上路,请多包涵

我发现自 Android Studio 4.1 以来,我无法通过在其 android:background 上设置颜色来更改 Button 的背景颜色,只是没有效果。自定义 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"/>

结果:

在此处输入图像描述

原文由 Sam Chen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 815
2 个回答

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

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

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

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

原文由 CommonsWare 发布,翻译遵循 CC BY-SA 4.0 许可协议

更新 03/2021

 app:backgroundTint="@null"    //just need this
android:background="@drawable/background_button"


好的,因为 MaterialButton 是默认的 Button 从 Android Studio 4.1 开始,我们可以使用 app:shapeAppearanceOverlay 属性修改形状。

1. 在 themes.xml 中创建自定义样式:

 <style name="leaf">
    <item name="cornerSizeTopLeft">70%</item>           //can specify corner position
    <!--<item name="cornerFamilyTopLeft">cut</item>-->
    <item name="cornerSizeBottomRight">70%</item>
    <!--<item name="cornerFamilyBottomRight">cut</item>-->
</style>

2. 在 Material Button 应用样式:

 <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="Show"
    app:shapeAppearanceOverlay="@style/leaf" />        //here

结果:

在此处输入图像描述

  • 有用的视频: https ://www.youtube.com/watch?v=jihLJ0oVmGo

原文由 Sam Chen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题