使用Android在xml中使用ShapeDrawable绘制多个形状

sky*_*oot 50 xml android shapes drawable

我目前正在代码中的自定义视图中在画布上绘制多个圆圈.圆圈是静态的,不会改变.我想在xml中使用ShapeDrawable绘制它们以帮助清理我的代码.我将有许多不同的drawable,用户可以选择,因此我不想在代码中这样做.有3或4 xml drawables似乎对我来说更整洁.

我使用ShapeDrawable在xml中创建了一个圆,但是无法向xml添加多个形状.

如何使用ShapeDrawable向xml文档添加多个形状.

Ken*_*ice 85

这是我用一个像素黑色边框填充红色圆圈的方法,中间有一个白色数字72:

在res\drawable中创建一个XML文件并对其进行适当命名,例如red_circle_black_border.xml

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@android:color/black" />
        </shape>
    </item>
    <item android:top="1dp" android:left="1dp" android:right="1dp" android:bottom="1dp">
        <shape android:shape="oval">
            <solid android:color="@android:color/red" />
        </shape>
    </item>
</layer-list>
Run Code Online (Sandbox Code Playgroud)

然后,要在布局中使用它,请按如下方式声明:

<TextView
    android:text="72"
    android:textSize="14dp"
    android:textStyle="bold"
    android:background="@drawable/red_circle_black_border" 
    android:layout_width="22dp"
    android:layout_height="22dp"
    android:gravity="center_vertical|center_horizontal"
    android:textColor="@android:color/white" />
Run Code Online (Sandbox Code Playgroud)

显然,根据需要更改textSize和layout_width/height :-)

  • 当然.它现在实际上只是一个可绘制的,所以像图像一样使用它. (2认同)

sky*_*oot 45

我想我找到了一个解决方案,使用Layer-list为我的xml文件添加多个形状.我还没试过这个,但这似乎正是我想要的,因为形状将按照它们的数组索引的顺序绘制.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
   <item>
      <shape>
         <solid android:color="#FFF8F8F8" />
      </shape>
   </item>
   <item android:top="23px">
      <shape>
         <solid android:color="#FFE7E7E8" />
      </shape>
   </item>
</layer-list>
Run Code Online (Sandbox Code Playgroud)

博客文章

Android文档