Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add headers in a listView using ArrayAdapter

Am trying to display a listview using array adapter. I get the array from the database.

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
   android.R.layout.simple_list_item_1, ArrayofName);
ListView myListView = (ListView) ll.findViewById(R.id.list1);
myListView.setAdapter(adapter);

Now i want to categorize them using the headers. I tried to add another array adapter. But it doesnt work for the headers.

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, ArrayofName);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, ArrayofName);
ListView myListView = (ListView) ll.findViewById(R.id.list1);
myListView.addHeaderView(adapter1);
myListView.setAdapter(adapter);

How can i get this to work?

PS : I am using a fragment.

like image 855
abc Avatar asked Dec 19 '22 12:12

abc


1 Answers

Sort the items in your adapter in the order you want to display them with the headers (SectionItem) in between the items.

Create a Person class and a SectionItem class.

Example of an adapter with persons and sections per first letter of the name:

- A (SectionItem)
- Adam (Person)
- Alex (Person)
- Andre (Person)
- B (SectionItem)
- Ben (Person)
- Boris (Person)
...

In the adapter.getViewTypeCount return 2. In the adapter.getItemViewType(position) return 0 for SectionItems and 1 for Persons. In the getView(...) return a view for a SectionItem or a Person.

Example:

public class SectionedAdapter extends BaseAdapter {

    ....

    @Override
    public int getViewTypeCount() {
        return 2; // The number of distinct view types the getView() will return.
    }

    @Override
    public int getItemViewType(int position) {
        if (getItem(position) instanceof SectionItem){
            return 0;   
        }else{
            return 1;
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Object item = getItem(position);
        if (item instanceof SectionItem) {
            if (convertView == null) {
                convertView = getInflater().inflate(R.layout.section, null);
            }
            // Set the section details.
        } else if (item instanceof Person) {
            if (convertView == null) {
                convertView = getInflater().inflate(R.layout.person, null);
            }
            // Set the person details.
        }
        return convertView;
    }
}
like image 175
userM1433372 Avatar answered Jan 09 '23 17:01

userM1433372