【问题标题】:Set background color and border color of Button using Shape Drawable in Android 8在 Android 8 中使用 Shape Drawable 设置 Button 的背景颜色和边框颜色
【发布时间】:2021-06-29 10:37:48
【问题描述】:

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

button_start.xml 文件:

activity_main.xml 文件:

结果:

【问题讨论】:

    标签: android xml button android-button border-color


    【解决方案1】:

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

            <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>
    


    长答案:
    如果你想使用背景形状,你必须添加app:backgroundTint="@null"
    比如:

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

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

    【讨论】:

    • 感谢您的解决方案,先生。但是,您能解释一下为什么我的方法不起作用吗?我想知道深刻理解的原因。
    • @ManhHai 使用材质组件主题(我想你正在使用它)Button 在运行时被替换为使用自己的背景的MaterialButton。您可以定义自定义背景(但这不是最佳选择),但为避免自定义背景不着色,您必须添加 app:backgroundTint="@null"。建议您使用所有默认功能的解决方案。更多信息here
    • @ManhHai 已更新所有详细信息。
    • 非常感谢您,先生。现在,我深深地明白了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 2020-01-25
    • 2015-07-05
    • 2013-08-04
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多