简体   繁体   English

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

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

I am trying to set background color and border color of Button using Shape Drawable (create button_start.xml in drawable) in Android 8, but it does not seem to work.我正在尝试在 Android 8 中使用 Shape Drawable 设置按钮的背景颜色和边框颜色(在 drawable 中创建 button_start.xml),但它似乎不起作用。

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

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

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

Short answer: .简短的回答:
You don't need to define a background shape, just use a MaterialButton with the shapeAppearanceOverlay attribute:您不需要定义背景形状,只需使用带有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"
            />

with:和:

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

在此处输入图像描述


Long answer:长答案:
If you want to use a background shape you have to add app:backgroundTint="@null" .如果你想使用背景形状,你必须添加app:backgroundTint="@null"
Something like:就像是:

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

Using a Material Components Theme the Button is replaced at runtime by a MaterialButton which use a own MaterialShapeDrawable as background.使用材质组件主题, Button在运行时由使用自己的MaterialButton作为背景的MaterialShapeDrawable替换。 You can define a custom background but to avoid that the custom background doesn't get tinted you have to add app:backgroundTint="@null" .您可以定义自定义背景,但为避免自定义背景不着色,您必须添加app:backgroundTint="@null"
The 2 solutions are not equivalent.两种解决方案不等价。
Using a custom android:background the default MaterialShapeDrawable is not used and some features like stroke, shapeappearance, ripple are not set (since they are related to the MaterialShapeDrawable ).使用自定义android:background不使用默认MaterialShapeDrawable并且未设置诸如笔画、形状外观、波纹等一些特征(因为它们与MaterialShapeDrawable相关)。 You have to provide them with your custom background.您必须为他们提供您的自定义背景。

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

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