繁体   English   中英

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

[英]Set background color and border color of Button using Shape Drawable in Android 8

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

button_start.xml 文件: 在此处输入图像描述

activity_main.xml 文件: 在此处输入图像描述

结果:
在此处输入图像描述

简短的回答:
您不需要定义背景形状,只需使用带有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作为背景的MaterialShapeDrawable替换。 您可以定义自定义背景,但为避免自定义背景不着色,您必须添加app:backgroundTint="@null"
两种解决方案不等价。
使用自定义android:background不使用默认MaterialShapeDrawable并且未设置诸如笔画、形状外观、波纹等一些特征(因为它们与MaterialShapeDrawable相关)。 您必须为他们提供您的自定义背景。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM