ViewHolder
一、新建类继承BaseAdapter
public class MyAdapter extends BaseAdapter{}
二、重载相关方法getCount()、getItem()、getItemId()、getView()
getCount()方法返回数据的长度(data.size/data.length())
三、新建class类ViewHolder
private class ViewHolder{}
四、ViewHolder中
1.定义所用到的相关控件
添加ViewHolder构造方法public ViewHolder(View convertView)
2.通过convertView绑定控件
this.tv1 = (TextView)convertView.findViewById(R.id.tv1);
this.tv2 = (TextView)convertView.findViewById(R.id.tv2);
this.iv = (ImageView)convertView.findViewById(R.id.iv);
五、getView()中进行处理相关操作
1.初始化ViewHolder对象为空
ViewHolder holder = null;
2.如果convertView为空,将布局文件转换成view
LayoutInflater inflater = LayoutInflater.from(context);
converView = inflater.inflate(layout,null);
3.将convertView赋给holder
holder = new ViewHolder(convertView);
4.给convertView设置标签
convertView.setTag(holder);
5.如果convertView不为空,直接获取标签
holder = (ViewHolder)convertView.getTag();
6.通过holder给控件赋值
holder.tv1.setText("第"+position+"天");
holder.tv2.setText("第"+position+"次");
holder.iv.setImageResource(imgId[position]);
六、添加新建类的构造方法,至少包含上下文环境、布局id、数据
public MyAdapter(Context context, List<String> data,int layoutId) {
super();
this.context = context;
this.data = data;
this.layoutId = layoutId;
}
七、在主Activity中,通过创建类对象传入相关参数
MyAdapter adapter = new MyAdapter(this,data,R.layout.list_item);
lv.setAdapter(adapter);