【问题标题】:Drawing multiple shapes with ShapeDrawable in xml with Android使用Android在xml中使用ShapeDrawable绘制多个形状
【发布时间】:2011-05-02 22:45:19
【问题描述】:

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

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

如何使用 ShapeDrawable 将多个形状添加到 xml 文档。

【问题讨论】:

    标签: android xml drawable shapes


    【解决方案1】:

    以下是我如何用一个像素的黑色边框制作一个实心红色圆圈,中间有一个白色数字 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 :-)

    【讨论】:

    • 如果您没有要显示的文字,我假设您可以使用图像视图?
    • 当然。它现在实际上只是一个可绘制对象,所以像图像一样使用它。
    • 请注意,您可以通过使用形状的描边(又名边框)元素来实现相同的效果:
    【解决方案2】:

    我想我找到了一种解决方案,可以使用 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>
    

    Blog post

    Android docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      相关资源
      最近更新 更多