因为每次使用ListView和BaseAdapter,都要重复的写很多代码,所以我写了一个万能的ViewHolder,而不要每次都要写一个Holder,
public class ViewHolder {
//用于保存子控件的容器
private SparseArray<View> mViews;
private int mPosition ;
private View mConvertView;
public ViewHolder(Context context , ViewGroup parent , int layouId , int position){
this.mPosition = position;
mViews = new SparseArray<View>();
mConvertView =
LayoutInflater.from(context).
inflate(layouId , parent ,false);
mConvertView.setTag(this);
}
/**
* 通过viewId获取到控件
* @param viewId
* @param <T>
* @return
*/
public <T extends View>T getView(int viewId){
View view = mViews.get(viewId);
if (view == null) {
view = mConvertView.findViewById(viewId);
mViews.put(viewId , view);
}
return (T) view;
}
/*
*获取到复用的ConvertView
*/
public View getConvertView() {
return mConvertView;
}
/**
*
* 复用Viewholder
*/
public static ViewHolder getViewHolder(Context context ,
int position, int layouId ,View convertView,
ViewGroup parent){
if (convertView == null){
return new ViewHolder(context , parent ,layouId ,
position);
}else {
ViewHolder viewHolder = (ViewHolder)
convertView.getTag();
viewHolder.mPosition = position;
return viewHolder;
}
}
}