Add margin above top ListView item (and below last) in Android
Space padding = new Space(this);
padding.setHeight(20); // Can only specify in pixels unfortunately. No DIP :-(
ListView myListView = (ListView) findViewById(R.id.my_list_view);
myListView.addHeaderView(padding);
myListView.addFooterView(padding);
myListView.setAdapter(myAdapter);
The above ListView will have a header and footer padding of 20 pixels.
Appendage to @Jakobud's answer...
My listView was already making use of the android:divider/android:dividerHeight
properties to create transparent gaps between listView items. This allowed me to simply add the android:headerDividersEnabled
and android:footerDividersEnabled
properties and set the Header and Footer views to new View(Activity.this)
.
Slight simplification for cases where you already have dividers setup in the listView.
My solution using a ListFragment
, based on the solutions by @Jakobud and @greg7gkb.
ListView listView = getListView();
listView.setDivider(null);
listView.setDividerHeight(getResources().getDimensionPixelSize(R.dimen.divider_height));
listView.setHeaderDividersEnabled(true);
listView.setFooterDividersEnabled(true);
View padding = new View(getActivity());
listView.addHeaderView(padding);
listView.addFooterView(padding);
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)