10

尝试使用 LayerDrawable(在 XML 中定义为图层列表)将多个形状可绘制对象分层;用作布局的背景。

Android 指南(用于 LayerList)说:

默认情况下,所有可绘制项都会缩放以适应包含视图的大小。因此,将图像放在图层列表中的不同位置可能会增加视图的大小,并且某些图像会适当缩放。为避免缩放列表中的项目,请使用<bitmap> 元素内的<item>元素来指定可绘制对象并将重力定义为不缩放的对象,例如“中心”。

我不希望我的形状按比例缩放,但我不确定如何bitmap正确地将它们包装在标签中:如果我按如下方式执行它会产生错误:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <bitmap
            android:src="@drawable/layer_one"
            android:gravity="center" />
    </item>
    <item>
        <bitmap
            android:src="@drawable/layer_two"
            android:gravity="center" />
    </item>
    <item>
        <bitmap
            android:src="@drawable/layer_three"
            android:gravity="center" />
    </item>
    <item>
        <bitmap
            android:src="@drawable/layer_four"
            android:gravity="center" />
    </item>
</layer-list>

投诉:

二进制 XML 文件第 25 行:<bitmap>需要有效的 src 属性

其中一个可绘制对象的示例,例如 res/drawable/layer_one.xml:

<?xml version="1.0" encoding="utf-8"?>

<!--  res/drawable/layer_one.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#FFFFFF"/>
    <corners
        android:bottomRightRadius="15dp"
        android:bottomLeftRadius="15dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp" />
</shape>

Android 站点上使用的示例使用图像作为可绘制对象,而不是 XML 定义的形状(并不是说我的错误是针对这些的,而且我没有在某处犯过愚蠢的错误)。任何线索表示赞赏,谢谢。


使用可绘制资源
这个问题的答案表明您不能将 XML 可绘制对象用作位图的 src。我已经修改了问题的标题,现在询问如何在不使用的情况下防止形状缩放(从而调整容器视图的大小)bitmap,或者我是否被迫使用实际的图像资源?


添加了所需结果的图像 - 能够拥有具有规则矩形填充形状或其他形状的背景,然后在此之上分层,更多形状可绘制对象(这里有 3 个椭圆)。左侧是理想的,允许顶部和左侧偏移,右侧很好,所有形状都转到默认位置:

在此处输入图像描述

4

1 回答 1

2

是的,(根据我之前的回答您不能将 xml drawable 用于位图。构建很好,但是当您运行应用程序时,它会崩溃。

关于声明use a <bitmap> element inside the <item> element意味着您可以在图层列表中定义更多形状,这就是它的用途。虽然您也可以定义位图,但您的位图应该有一个src值,指的是实体图像(而不是 xml)。

您可以做的是将 layer_one、layer_two 和其他层的 xml 插入到您的 layer_list xml 中。例如:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape
            android:shape="rectangle" >
            <solid android:color="#FFFFFF" />

            <corners
                android:bottomLeftRadius="15dp"
                android:bottomRightRadius="15dp"
                android:topLeftRadius="15dp"
                android:topRightRadius="15dp" />
        </shape>
    </item>

    <!-- and so on with your other shapes -->

</layer-list>

希望它应该工作:)

于 2012-04-07T18:22:23.877 回答