Add headers to listView using ArrayAdapter

I am trying to display a list using an array adapter. I get an 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 classify them using headings. I tried to add another array adapter. But it does not work for headlines.

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 make this work?

PS: I use a snippet.

+4
source share
2 answers

Sort the elements in your adapter in the order in which you want to display them with headings (SectionItem) between the elements.

Create a Person class and a SectionItem class.

An example of an adapter with faces and sections on the first letter of a name:

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

adapter.getViewTypeCount return 2. adapter.getItemViewType(position) 0 SectionItems 1 . getView (...) SectionItem Person.

:

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;
    }
}
+9

( ), mylistview.AddHeaderView( )

, "" . , .

, , , , .

/ ListView?

+1

All Articles