I have a BaseAdapter that manages the rows in my ListView. All this while I’ve been displaying the records in the listview without any grouping or headers and it has worked fine. My adapter uses an ArrayList and for a non-grouped set of data, it works just fine. Here’s what it looks like:
public class SearchResultsAdapter extends BaseAdapter {
public ArrayList<Result> objResults;
public SearchResultsAdapter(Search ctxContext, ArrayList<Result> objResults) {
this.objResults = objResults;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (check whether it is a category) {
View v = mInflater.inflate(R.layout.category, null);
final TextView sectionView = (TextView) v.findViewById(R.id.text);
sectionView.setText("New Category");
return v;
} else {
View vewRow = mInflater.inflate(R.layout.row, null);
TextView tvwName = (TextView) vewRow.findViewById(R.id.name);
tvwName.setText(objResults.get(position).getName());
return vewRow;
}
}
}
When the getView method of the adapter is invoked internally, it only expects it to return a single row from my collection at that position.
Ideally I could has used a HashMap as I could have grouped my data and stored the data of each group under a key in the map but I can’t reference HashMap items by a simple position as I can with an ArrayList; it’s only logical.
I’ve seen a lot of apps use the ListView to show both headers and rows but I haven’t understood what collection/pattern is best suited for this.
Thanks.
As per Samir’s comment and example:
Create and an
ArrayListof a custom Interface. Create two classes –RowandSectionthat implement that custom Interface and then when returning the row in thegetViewmethod of theBaseAdapter, return the correct view i.e. row or section based whether the object in the list at that position is aRowor aSection.