Android之Adapter用法总结
2012-07-25 10:01:41 来源:WEB开发网核心提示:public class MyListView3 extends ListActivity { // private List<String> data = new ArrayList<String>(); @Override public void o
public class MyListView3 extends ListActivity { // private List<String> data = new ArrayList<String>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SimpleAdapter adapter = new SimpleAdapter(this,getData(),R.layout.vlist, new String[]{"title","info","img"}, new int[]{R.id.title,R.id.info,R.id.img}); setListAdapter(adapter); } private List<Map<String, Object>> getData() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); map.put("title", "G1"); map.put("info", "google 1"); map.put("img", R.drawable.i1); list.add(map); map = new HashMap<String, Object>(); map.put("title", "G2"); map.put("info", "google 2"); map.put("img", R.drawable.i2); list.add(map); map = new HashMap<String, Object>(); map.put("title", "G3"); map.put("info", "google 3"); map.put("img", R.drawable.i3); list.add(map); return list; } }
使用simpleAdapter的数据用一般都是HashMap构成的List,list的每一节对应ListView的每一行。HashMap的每个键值数据映射到布局文件中对应id的组件上。因为系统没有对应的布局文件可用,我们可以自己定义一个布局vlist.xml。下面做适配,new一个SimpleAdapter参数一次是:this,布局文件(vlist.xml),HashMap的 title 和 info,img。布局文件的组件id,title,info,img。布局文件的各组件分别映射到HashMap的各元素上,完成适配。
运行效果如下图:
3)SimpleCursorAdapter
public class SimpleCursorAdapterActivity extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //获得一个指向系统通讯录数据库的Cursor对象获得数据来源 Cursor cur = getContentResolver().query(People.CONTENT_URI, null, null, null, null); startManagingCursor(cur); //实例化列表适配器 ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cur, new String[] {People.NAME}, new int[] {android.R.id.text1}); setListAdapter(adapter); } }
更多精彩
赞助商链接