Add margin above top ListView item (and below last) in Android

Mick Byrne picture Mick Byrne · Jun 9, 2011 · Viewed 46.8k times · Source

This is a pretty fine question about the layout of items in a ListView in Android.

I have an activity with a title bar at the top and a ListView taking up the rest of the screen. I want my ListView to appear with 10dp padding on the left, right and top, but when you scroll the ListView up, I want it to cover the top 10dp padding before disappearing under the faded edge. Similarly, when you scroll to the bottom, the last list item should appear with 10dp between the bottom of the last list item and the actual bottom of the screen (if you're wondering why, it's because there's a pretty background image that I want poking out around the ListView).

I've tried adding padding to the ListView itself, but then when you scroll the list it disappears under the edge of the padding.

I'm from a web dev background, and the analogy would be to add margin above the first list item (and below the last list item).

Answer

Gunnar Karlsson picture Gunnar Karlsson · Jan 22, 2013

You wrote:

I've tried adding padding to the ListView itself, but then when you scroll the list it disappears under the edge of the padding.

Set ListView's clipToPadding attribute to false. This will enable padding around the ListView and scrolling to the end of the layout (and not only to the edge of the padding).

An example:

<ListView
    android:id="@+id/list_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:divider="@android:color/transparent"
    android:dividerHeight="10.0sp"
    android:padding="16dip"
    android:clipToPadding="false"/>

android:clipToPadding is an XML attribute of ViewGroup, the base class for layouts and views containers.

The related method call is:

public void setClipToPadding (boolean clipToPadding)