Harsh Patel Harsh Patel - 1 month ago 7
Android Question

Use list view with headers in a layout with margins

I just started learning a little bit of Android. I am currently trying to use List Views with section headers. I found this reusable code at this website :

http://javatechig.com/android/listview-with-section-header-in-android

It uses two layout files: snippet_item1.xml and snippet_item2.xml.

The result looks like this:

ListView with Section Headers

I want this page to have a margin from the top of 100dp. I have tried adding margin_top and padding to both xml files but I don't get the desired results.

What do you think?

Answer

Instead of extending from ListActivity, extend your class from a simple Activity and in that activity put a ListView, you can give margins and padding to ListView. Just use the same adapter you have already created with the ListView. Here is how. This is your activity's layout file, call it activity_list.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         android:orientation="vertical"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:background="#fff">
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:marginTop="20sp"
        android:marginBottom="10sp"
        android:divider="@android:color/transparent"
        android:id="@+id/listview"
        android:padding="5sp"
        android:dividerHeight="5.0sp"
     ></ListView>
    </RelativeLayout>

Now create an Activity in Java.

    public class MyListActivity extends Activity {
         private ListView listView;
         private MyAdapter myAdapter;
         protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_list);
              this.listView = (ListView) findViewById(R.id.listview);
              this.myAdapter = new MyAdapter(getApplicationContext());
              //add whatever you want to add to your adapter
              listView.setAdapter(myAdapter);
         }
    }

I hope this solves your problem!