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

问题描述 投票:0回答:2

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

button_start.xml 文件:

activity_main.xml 文件:

结果:

android xml button colors android-button
2个回答
5
投票

简短回答:.
您不需要定义背景形状,只需使用

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>


长答案:
如果你想使用背景形状,你必须添加

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"

这 2 个解决方案并不等效。
使用自定义
android:background
时,不会使用默认的
MaterialShapeDrawable
,并且不会设置某些功能,如描边、形状外观、波纹(因为它们与
MaterialShapeDrawable
相关)。您必须向他们提供您的自定义背景。


0
投票

您需要在形状中设置

solid
属性:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
    android:width="2dp"
    android:color="#4E008E" />
<corners android:radius="8dp" />
<solid android:color="@color/white"/>
© www.soinside.com 2019 - 2024. All rights reserved.