Search code examples
androidandroid-listviewshapesdivider

Android - only the last item shows in layer-list


I'm trying to style the divider for ListView. What I want is just 2 simple horizontal lines.

list.xml

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/ListView" >
</ListView>

styles.xml

<style name="ListView" parent="android:style/Widget.ListView">
    <item name="android:divider">@drawable/divider</item>

    <!-- 5dp: just to make sure there's enough space -->
    <item name="android:dividerHeight">5dp</item>
</style>

divider.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#00ffff" />
            <size android:height="1dp" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ff0000" />
            <size android:height="1dp" />
        </shape>
    </item>
</layer-list>

The result is a horizontal line with height of 5dp(should be 2, isn't it?) and color of red(color of second item). The first item with color #00ffff does not show up at all.

Can someone please suggest the code for 2 simple horizontal lines?


Solution

  • I'd better answer my own question...

    It seems styles.xml - style - item takes the color of the last item in layer-list as background for the entire divider. This last item is on top of other layers, and that is why other items in the layer-list don't show up.

    The key is padding.

    styles.xml

    <style name="ListView" parent="android:style/Widget.ListView">
        <item name="android:divider">@drawable/divider</item>
        <item name="android:dividerHeight">10dp</item>
    </style>
    

    divider.xml

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item>
            <shape android:shape="rectangle">
                <solid android:color="#0000ff" />
                <padding android:top="5dp"/>
            </shape>
        </item>
    
        <item>
            <shape android:shape="rectangle">
                <solid android:color="#ff0000" />
            </shape>
        </item>
    
    </layer-list>
    

    divider

    So in my case I just need to change 10dp/5dp to 2dp/1dp to get 2 thin horizontal lines.