How do I create a ListView with dashed / dotted line dividers in Android?
Asked Answered
P

3

13

I managed to figure out how to create a custom shape (with a dashed stroke) by creating a file called dash.xml inside of the /app/res/drawable/ folder:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <stroke
        android:color="#534b4b"
        android:width="1dp"
        android:dashGap="2dp"
        android:dashWidth="1dp"
    />
    <size
        android:height="1dp"
    />
</shape>

Now I'm confused as to how to apply this shape to a ListView. I've tried the following, but no divider is displayed:

<ListView android:id="@+id/android:list" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:cacheColorHint="#00000000"
    android:divider="@drawable/dash"
    android:dividerHeight="1dp"
/>

Wtf?

Parturient answered 8/11, 2010 at 0:35 Comment(0)
A
34

Here is mine and it works :

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <stroke
        android:color="#FF404040"
        android:width="1dp"
        android:dashGap="3dp"
        android:dashWidth="1dp"
    />
    <size
        android:height="3dp"
    />
</shape>
Aude answered 31/3, 2011 at 14:28 Comment(4)
You may also need to add android:layerType="software" to the node that is referencing the shape. At least on some devices the dotted line will appear solid.Hali
As an example of a device on which layerType solves solid line problem is Nexus 5 with 4.4.3.Bonnie
This version seems to work because of the height="3dp". This looks like a bug in GradientDrawable to me: if the height - 2 * the stroke width is <= 0, the line won't be drawn. This actually makes sense for a rectangle shape, but imho not for a line.Shimmery
Also, as mentioned before, you have to use a software layer for newer android versions, because the hardware acceleration does not support dashed lines. See code.google.com/p/android/issues/detail?id=29944Shimmery
R
7

You also need android:dividerHeight. Shapes are variable size, and right now you have a zero-height divider.

Relent answered 8/11, 2010 at 0:50 Comment(1)
Shoot, I forgot to add that in my example above, but when testing, a dividerHeight was included. Thank you for pointing that out!Parturient
J
2
  1. Define layerType for show the dotted line divider don't forget to give divider height.

<ListView android:id="@+id/android:list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:cacheColorHint="#00000000" android:divider="@drawable/dash" android:dividerHeight="1dp" android:layerType="software"/>

Janeth answered 14/7, 2015 at 15:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.