我目前正在代码中的自定义视图中的画布上绘制多个圆圈。圆圈是静态的,不会改变。我想使用 xml 中的 ShapeDrawable 来绘制它们,以帮助清理我的代码。我将有许多不同的可绘制对象供用户选择,因此我不想在代码中执行此操作。拥有 3 或 4 个 xml drawable 对我来说似乎更整洁。
我使用 ShapeDrawable 在 xml 中创建了一个圆圈,但无法向 xml 添加多个形状。
如何使用 ShapeDrawable 将多个形状添加到 xml 文档。
下面是我如何用一个像素的黑色边框制作一个实心红色圆圈,中间有一个白色数字 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>
然后,要在您的布局中使用它,请按如下方式声明它:
<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" />
显然,根据需要更改 textSize 和 layout_width/height :-)
我想我找到了一种解决方案,可以使用 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>