62

我不明白图层列表是如何工作的。我阅读了带有一些示例的官方文档,但它并不像预期的那样对我有用。我想要四个应该用 1dp 填充的正方形,但没有什么是预期的。这是一个放大 500% 的屏幕截图:

我的苏亚雷斯
(错误的颜色无关紧要)
如您所见,尺寸完全错误,并且缺少填充物。我试图设置真正的值,如宽度/高度和右/左/顶部/按钮,以确保 android 得到我想要的点。

这是我的xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">
        <shape android:shape="rectangle">
            <size android:width="9dp"
                android:height="9dp"/>
            <solid android:color="#f000"/>
        </shape>
    </item>

    <item android:top="1dp" android:left="1dp" android:bottom="5dp" android:right="5dp">
        <shape android:shape="rectangle">
            <size android:width="3dp"
                android:height="3dp"/>
            <solid android:color="#f00"/>
        </shape>
    </item>
    <item android:top="1dp" android:left="5dp" android:bottom="5dp" android:right="1dp">
        <shape android:shape="rectangle">
            <size android:width="3dp"
                android:height="3dp"/>
            <solid android:color="#0f0"/>
        </shape>
    </item>

    <item android:top="5dp" android:left="1dp" android:bottom="1dp" android:right="5dp">
        <shape android:shape="rectangle">
            <size android:width="3dp"
                android:height="3dp"/>
            <solid android:color="#0f0"/>
        </shape>
    </item>
    <item android:top="5dp" android:left="5dp" android:bottom="1dp" android:right="1dp">
        <shape android:shape="rectangle">
            <size android:width="3dp"
                android:height="3dp"/>
            <solid android:color="#f00"/>
        </shape>
    </item>
</layer-list>
4

2 回答 2

108

左、上、右和下的值是从它们各自的边缘测量的。

所以 left=0dp, top=0dp, bottom=0dp & right=50dp 会给你一个 (match_parent - 50dp) 宽而不是 50dp 宽的矩形。因此,“正确”的较大值实际上会给您一个较小的矩形。

这同样适用于其他值,但在大多数情况下,它们的行为与预期的一样,它只是“正确”,可能会引起混淆。

于 2013-06-04T01:59:46.340 回答
6

您可以使用px代替dp或将所有维度乘以10.

我很惭愧地承认我不完全知道为什么会这样,但我的猜测是它与密度有关,其中1dp是一个浮动px值并且ImageView按比例放大。

欢迎专家回答:)

于 2013-01-21T12:27:59.067 回答