如何在xml中设置形状的背景?

Waz*_*_Be 38 android background colors shape android-drawable

我刚刚使用android形状创建了一个红色圆圈:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadiusRatio="4"
    android:shape="ring"
    android:thicknessRatio="9"
    android:useLevel="false" >

     <solid android:color="#FF0000" />

    <size
        android:height="48dip"
        android:width="48dip" />

</shape>
Run Code Online (Sandbox Code Playgroud)

这真的很酷,但我无法将圆圈的背景颜色设置为我的颜色.我尝试过,android:background="#FFFFFF"但在我的布局中看起来总是黑色.如何设置上述形状的背景?

Luk*_*rog 74

我认为一个layer-list可能会帮助你:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#ffffff" />
        </shape>
    </item>
    <item>
        <shape
            android:innerRadiusRatio="4"
            android:shape="ring"
            android:thicknessRatio="9"
            android:useLevel="false" >
            <solid android:color="#FF0000" />
            <size
                android:height="48dip"
                android:width="48dip" />
        </shape>
    </item>

</layer-list>
Run Code Online (Sandbox Code Playgroud)


Gen*_* Bo 12

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners android:radius="12dp" />
    <solid android:color="#ffffff" />
    <stroke
        android:width="1dp"
        android:color="@android:color/black" />

</shape>
Run Code Online (Sandbox Code Playgroud)


Har*_*eet 5

我只是添加有用的研究作为答案。让我们假设您有一个@GeneBoshape描述的答案,并且您期待重新使用该形状但具有不同的颜色。因此,您需要在小部件中做的就是:solid

android:background="@drawable/your_shape_to_reuse"
android:backgroundTint="@color/new_background_color_you_need"
Run Code Online (Sandbox Code Playgroud)

  • 您可能还想添加 android:backgroundTintMode="screen" 或其他模式。 (2认同)