The technique of supplying an alternate layout to use for rows
handles simple cases very nicely. However, what if we want the icon to
change based on the row data? For example, suppose we want to use one
icon for small words and a different icon for large words. In the case
of ArrayAdapter, we will need to extend it, creating our own custom subclass (e.g., IconicAdapter) that incorporates our business logic. In particular, it will need to override getView().
The getView() method of an Adapter is what an AdapterView (like ListView or Spinner) calls when it needs the View associated with a given piece of data the Adapter is managing. In the case of an ArrayAdapter, getView() is called as needed for each position in the array—"get me the View for the first row," "get me the View for the second row," and so forth.
As an example, let's rework the code in the preceding section to use getView(), so we can show different icons for different rows—in this case, one icon for short words and one for long words (from the FancyLists/Dynamic sample project):
public class DynamicDemo extends ListActivity {
TextView selection;
private static final String[] items={"lorem", "ipsum", "dolor",
"sit", "amet",
"consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis",
"etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new IconicAdapter());
selection=(TextView)findViewById(R.id.selection);
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
selection.setText(items[position]);
}
class IconicAdapter extends ArrayAdapter<String> {
IconicAdapter() {
super(DynamicDemo.this, R.layout.row, R.id.label, items);
}
public View getView(int position, View convertView,
ViewGroup parent) {
View row=super.getView(position, convertView, parent);
ImageView icon=(ImageView)row.findViewById(R.id.icon);
if (items[position].length()>4) {
icon.setImageResource(R.drawable.delete);
}
else {
icon.setImageResource(R.drawable.ok);
}
return(row);
}
}
}
Our IconicAdapter—an inner class of the activity—has two methods. First, it has the constructor, which simply passes to ArrayAdapter the same data we used in the ArrayAdapter constructor in StaticDemo. Second, it has our getView() implementation, which does two things:
It chains to the superclass's implementation of getView(), which returns to us an instance of our row View, as prepared by ArrayAdapter. In particular, our word has already been put into the TextView, since ArrayAdapter does that normally.
It finds our ImageView and applies a business rule to set which icon should be used, referencing one of two drawable resources (R.drawable.ok and R.drawable.delete).
The result of our revised example is shown in Figure 1.