//抽象封装ViewHolder
public class MyViewHolder {private SparseArray<View> mViews;
private View mconvertView;
public MyViewHolder(Context context, int layoutId) {
super();
mViews = new SparseArray<View>();
this.mconvertView = View.inflate(context, layoutId, null);
mconvertView.setTag(this);
}
public static MyViewHolder getHolder(Context context, View convertView,
int layoutId) {
if (convertView == null) {
return new MyViewHolder(context, layoutId);
} else {
return (MyViewHolder) convertView.getTag();
}
}
public View getView(int ViewID) {
View view = mViews.get(ViewID);
if (view == null) {
view = mconvertView.findViewById(ViewID);
mViews.put(ViewID, view);
}
return view;
}
public View getConvertView() {
return mconvertView;
}
}
//adapter
public abstract class MyAdapter<T> extends BaseAdapter {private Context context;
private ArrayList<T> data;
private int layoutId;
public MyAdapter(Context context, ArrayList<T> data, int layoutId) {
super();
this.context = context;
this.data = data;
this.layoutId = layoutId;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
@Override
public T getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder holder = MyViewHolder.getHolder(context, convertView,
layoutId);
convert(holder, getItem(position));
return holder.getConvertView();
}
public abstract void convert(MyViewHolder holder, T bean);
}
//使用方法
list_view = (ListView) findViewById(R.id.list_view);
list_view.setAdapter(new MyAdapter<Bean>(MainActivity.this, data,
R.layout.item) {
@Override
public void convert(MyViewHolder holder, Bean bean) {
TextView title = (TextView) holder.getView(R.id.title);
title.setText(bean.getTitle());
TextView desc = (TextView) holder.getView(R.id.desc);
desc.setText(bean.getDesc());
TextView time = (TextView) holder.getView(R.id.time);
time.setText(bean.getTime());
TextView phone = (TextView) holder.getView(R.id.phone);
phone.setText(bean.getPhone());
}
});