Reputation: 113
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.
Upvotes: 4
Views: 5641
Reputation: 5497
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;
}
}
Upvotes: 10
Reputation: 12900
You want to add Headers ( as in plural) but you are calling mylistview.AddHeaderView (as in singular)
That method accepts a single view that is shown 'above' your first item. You can inflate a resource or create a view at runtime to add it tot the top of your list.
If you want to add multiple headers, like in section headers, you have to create a custom arrayadapter which inserts those for you at the right position.
An example can be found here How to add section separators / dividers to a ListView?
Upvotes: 1