Search code examples
androidheaderfooterlistactivityfixed

Android ListActivity - fixed header and footer


Is it possible to set header and footer at ListActivity to be fixed at the top and the bottom, so only the content (list) is scrolling, not also header and footer?

I have both set like this:

View header = getLayoutInflater().inflate(R.layout.list_header, null);
View footer = getLayoutInflater().inflate(R.layout.list_footer, null);
ListView listView = getListView();
listView.addHeaderView(header);
listView.addFooterView(footer);

Solution

  • You can achieve it by using a custom XML layout in which you will set the layout of your header, footer and list.

    Note that to be compatible with ListActivity this layout must contain a ListView with the id android.R.id.list:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="HEADER" />
    
        <ListView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="FOOTER" />
    
    </LinearLayout>
    

    And set it in your ListActivity like this:

    public class TestActivity extends ListActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    }