1.创建CommonAdapter类:
public abstract class CommonAdapter02<T> extends BaseAdapter {
protected Context mContext;
protected List<T> datas;
protected LayoutInflater mInflater;
public CommonAdapter02(Context context, List<T> datas) {
this.datas = datas;
mContext = context;
mInflater = LayoutInflater.from(context);
this.datas = datas;
}
@Override
public int getCount() {
return datas.size();
}
@Override
public T getItem(int position) {
return datas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
/*
* 优化方法二
* */
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = ViewHolder.get(mContext, convertView, parent,R.layout.item_simple_tv,position);
convert(holder,getItem(position));
return holder.getConvertView();
}
public abstract void convert(ViewHolder holder,T t);
}
public class ViewHolder {
private SparseArray<View> mViews;
private int mPosition;
private View mConvertView;
public View getConvertView() {
return mConvertView;
}
/**
* 通过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;
}
public ViewHolder(Context context, ViewGroup parent, int layoutId, int position) {
this.mPosition = position;
this.mViews = new SparseArray<>();
mConvertView = LayoutInflater.from(context).inflate(layoutId,parent,false);
mConvertView.setTag(this);
}
public static ViewHolder get(Context context, View convertView
, ViewGroup parent, int layoutId, int position) {
if (convertView == null) {
return new ViewHolder(context,parent,layoutId,position);
}else {
ViewHolder holder = (ViewHolder) convertView.getTag();
// 解决试图复用问题
holder.mPosition = position;
return holder;
}
}
}
public class MyAdapter03 extends CommonAdapter02<String> {
public MyAdapter03(Context context, List<String> datas) {
super(context, datas);
}
@Override
public void convert(ViewHolder holder, String o) {
TextView textView = holder.getView(R.id.id_recyclerView);
textView.setText(o);
}
}