The busy coders guide to android development feb 2009

Page 118

Getting Fancy With Lists

Using ViewWrapper is a matter of creating an instance whenever we inflate a row and attaching said instance to the row View via setTag(), as shown in this rewrite of getView(): public class ViewWrapperDemo extends ListActivity { TextView selection; 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(this)); selection=(TextView)findViewById(R.id.selection); } private String getModel(int position) { return(((IconicAdapter)getListAdapter()).getItem(position)); } public void onListItemClick(ListView parent, View v, int position, long id) { selection.setText(getModel(position)); } class IconicAdapter extends ArrayAdapter<String> { Activity context; IconicAdapter(Activity context) { super(context, R.layout.row, items); this.context=context; } public View getView(int position, View convertView, ViewGroup parent) { View row=convertView; ViewWrapper wrapper=null; if (row==null) { ViewInflate inflater=context.getViewInflate(); row=inflater.inflate(R.layout.row, null, null); wrapper=new ViewWrapper(row); row.setTag(wrapper);

} else { wrapper=(ViewWrapper)row.getTag();

97

This document is licensed for Cheng Po-wen's exclusive use by CommonsWare, LLC


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.