在项目中用到过多次ListView显示一项项的结构化数据,但是都用的比较浮云。今天特意系统的查看了一下各种Adapter用法,总结如下。
Adapter是联系前台View与后台数据的枢纽,后台数据在Adapter中的每一项建立联系,再将Adapter与前台ListView绑定。
1.首先创建一个继承BaseAdapter的类,也可以直接使用官方提供的子类,但是自己写的会比较灵活吧~
继承后需要重写以下4个函数:
public int getCount() 返回Adapter中的项数
public Object getItem(int pos) 返回pos位置处的对象,常常返回null(?)
public long getItemId(int pos) 返回pos位置那一项的id(如果是从数据库中读数据就返回id)
public View getView(int position, View convertView, ViewGroup parent)
返回position对应的View对象,convertView似乎用作返回对象
2.BaseAdapter子类中,需要有List<Map<String,Object>> 对象用于存放数据,在getView中从该对象中取出数据设置给各个View控件。
3.创建一个xml布局文件,用于设置Adapter中每一项应有布局样式,在getView中通过findViewById找到各个控件
4.主Activity中,创建一个List<Map<String,Object>>对象用于加入数据,传给BaseAdapter的子类。并将main.xml中ListView调用setAdapter方法与自己写的BaseAdapter子类绑定。
参考链接: