Android dashed divider in ListView

2019-05-26 17:30发布

问题:

I'd like to draw dashed dividers for the listview. But I failed. There are a few similar questions in StackOverflow, but none of them fixed my problem.

Here are the steps I create the dashed divider:

  • Create a list_divider.html

    <?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item>
        <shape android:shape="line">
            <stroke
                android:color="#ff0000"
                android:dashWidth="10px"
                android:dashGap="10px" />
        </shape>
    </item> </layer-list>
    
  • My layout contains the list view

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@android:id/list"
        android:layout_gravity="center_horizontal"
        android:footerDividersEnabled="true"
        android:divider="@drawable/list_divider"
        android:dividerHeight="1px"/>
    

Then in the preview inside the UI editor, it's like it works:

  • 3.But unfortunate it doesn't work in emulator:

Can anybody give me a hint? Thanks.

P.S.: The reason I'm using layer-list is that I may need to draw 2 lines in the future.

回答1:

Its documented here: https://code.google.com/p/android/issues/detail?id=29944

You have 2 options:

  • turn off hardware acceleration: android:hardwareAccelerated="false"
  • or: listView.setLayerType(View.LAYER_TYPE_SOFTWARE, null) or xml android:layerType="software"

It gave me too a headache!



回答2:

Did you name the drawable realy list_divider.html? Rename it to list_divider.xml. I'm surprised that it works in the UI editor.

A second thing which might have an impact: for the sizing of the divider use dp instead of px as units. In Listview and in divider xml. You never know how much 10 pixel are.