Android: in drawable xml, layer-list, why does the

2019-05-19 06:58发布

<layer-list
xmlns:android="http://schemas.android.com/apk/res/android"
>
<!--width here doesn't work-->
<item
    android:gravity="left"
    android:width="10dp"
    >
    <shape
        android:shape="rectangle"
    >
        <stroke
            android:width="1dp"
            android:color="@color/black"
        />
        <!--<gradient-->
            <!--android:startColor="#00dddddd"-->
            <!--android:endColor="#40404040"-->
            <!--android:angle="0"-->
            <!--/>-->
    </shape>
</item>
<!--width here doesn't work-->
<item
    android:width="10dp"
    android:gravity="right"
    >
    <shape
        android:shape="rectangle"
    >
        <stroke
            android:width="1dp"
            android:color="@color/black"
        />
        <!--<gradient-->
            <!--android:startColor="#00dddddd"-->
            <!--android:endColor="#40404040"-->
            <!--android:angle="180"-->
            <!--/>-->
    </shape>
</item>

Here is the example.

It works in Lollipop or higher, but it doesn't work in Kitkat, the width is being ignored, the rectangle will fill the whole view.

I also tried to remove the second item, only leaves the first item, the width is still being ignored.

The ImageView uses this drawable:

<!--Width will be changed dynamically-->
<ImageView
    android:id="@+id/someid"
    android:layout_width="100dp"
    android:layout_height="@dimen/someheight"
    android:src="@drawable/the_xml_above"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:clickable="false"
    />

How to solve this?

1条回答
手持菜刀,她持情操
2楼-- · 2019-05-19 07:22

Alright, I'll answer my own question:

It seems that on Android 4.4 or below, size node or width/height attribute will be ignored.
So the best approach is: create different shapes in different drawable xml files, create a relative layout instead of ImageView, and combine them in relative layout.

<RelativeLayout
    android:id="@+id/id1"
    android:layout_width="30dp"
    android:layout_height="@dimen/someheight"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:clickable="false">

    <ImageView
        android:layout_width="3dp"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:src="@drawable/somesrc"/>

    <ImageView
        android:layout_width="3dp"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:rotation="180"
        android:src="@drawable/somesrc"/>

</RelativeLayout>
查看更多
登录 后发表回答