在 Android 8 中使用 Shape Drawable 设置按钮的背景颜色和边框颜色

问题描述

我正在尝试在 Android 8 中使用 Shape Drawable(在 drawable 中创建 button_start.xml)设置 Button 的背景颜色和边框颜色,但它似乎不起作用。

button_start.xml 文件

enter image description here

activity_main.xml 文件

enter image description here

结果:

enter image description here

解决方法

简答:.
您不需要定义背景形状,只需使用带有 MaterialButton 属性的 shapeAppearanceOverlay

        <com.google.android.material.button.MaterialButton
            android:layout_width="100dp"
            android:layout_height="100dp"
            style="@style/Widget.MaterialComponents.Button"
            app:backgroundTint="@color/...."
            app:strokeColor="@color/...."
            app:strokeWidth="5dp"
            android:padding="0dp"
            android:insetLeft="0dp"
            android:insetTop="0dp"
            android:insetRight="0dp"
            android:insetBottom="0dp"
            android:text="BUTTON"
            app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MyApp.Button.Circle"
            />

与:

<style name="ShapeAppearanceOverlay.MyApp.Button.Circle" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">50%</item>
</style>

enter image description here


长答案:
如果要使用背景形状,则必须添加 app:backgroundTint="@null"
类似的东西:

<Button
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@drawable/shape_oval"
    app:backgroundTint="@null"

使用 Material 组件主题,Button 在运行时被 MaterialButton 替换,MaterialShapeDrawable 使用自己的 app:backgroundTint="@null" 作为背景。 您可以定义自定义背景,但为了避免自定义背景没有着色,您必须添加 android:background
这两种解决方案并不等效。
使用自定义 MaterialShapeDrawable 不使用默认 MaterialShapeDrawable 并且未设置某些功能,如笔画、形状外观、波纹(因为它们与 npx nodemon 相关)。您必须为他们提供您的自定义背景。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...