Step 1: Create a layout xml for the header and footer as per your requirement.
header.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?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="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:text="HEADER" android:background="#cf9f99" /> </LinearLayout> |
footer.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?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="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:text="FOOTER" android:background="#cf9f99" /> </LinearLayout> |
Step 2: Now let’s inflate these header and footer views and add it to our list view .
1 2 3 4 5 6 7 |
LayoutInflater inflater = getLayoutInflater(); ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, listView, false); ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView, false); listView.addHeaderView(header, null, false); listView.addFooterView(footer, null, false); |
Complete Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public class MainActivity extends Activity { ListView listView; static final String[] numbers = new String[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty one", "twenty two" }; View header; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.list_id); //code to add header and footer to listview LayoutInflater inflater = getLayoutInflater(); ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, listView, false); ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView, false); listView.addHeaderView(header, null, false); listView.addFooterView(footer, null, false); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, numbers); listView.setAdapter(adapter); } } |
Recent Comments