I am trying to modify the sample code below. It currently populates a View that contains an imageview and a textview. I have added an additional textview to my XML layout and am trying to figure out how to replace the simple array with a hash map or even a multidimensional array to populate not just the imageview and the first textview but also the second one.
I would appreciate sample code that shows the entire process. Thanks!
public class DynamicDemo extends ListActivity {
TextView selection;
private static final String[] items={"lorem", "ipsum", "dolor",
"sit", "amet"}
@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);
}
}
}
The easiest thing to do is use an
ArrayAdapter<MyDataObject>whereAnd then you would change
itemsto aMyDataObject[] itemsstored in your class, and instead of doingsuper.getView(index)you’d doitems[index](which would yield aMyDataObject) and use that data instead.Also, importantly: you should use the convertView. And possibly the ViewHolder pattern.
Edit: At OP’s request, a little more elaboration. Note that this uses the convertView pattern but not the ViewHolder pattern (you should be able to adopt that fairly easily).
In your
Adapter, you’d changegetView()as follows:That’s it for the easy way, and quite similar to what you have.
Some more detail; if you don’t care, skip it. 🙂
I know that Adapters can seem magical, so in the interest of showing how
ListViewadapters work, here’s an example using aListinstead of anArray, so we can remove any magic thatArrayAdapterdoes with the array behind the scenes. I use aListbecause they can be more versatile for whatever you’re trying to accomplish (ArrayListorLinkedListor what-have-you).To use a
Listyou’d have the following in yourActivity:And instead of
items[position]you’d useIf you want to change your data set dynamically, you should probably use this approach (keeping
myListat theActivitylevel) instead of using an Array and an ArrayAdapter. That would mean you’d need to change from extendingArrayAdapter<String>to just extendingBaseAdapter<MyDataObject>(most of the methods inBaseAdapterare trivial to implement) since our data size, for example, would be determined by our list, and not theArrayAdapter‘s array.I know that’s kind of a fire hose, but let me know if you have any questions!