首先写一个通用的ViewHolder
public class CommonViewHolder {
private final SparseArray<View> mViews;
private View mConvertView;
private int mPosition;
public CommonViewHolder(Context context,ViewGroup parent,int layoutID,int position) {
this.mViews = new SparseArray<>();
mConvertView = LayoutInflater.from(context).inflate(layoutID,parent,false);
mConvertView.setTag(this);
mPosition = position;
}
public static CommonViewHolder get(Context context,View convertView,ViewGroup parent,int layoutID,int position){
if(convertView == null){
return new CommonViewHolder(context,parent,layoutID,position);
}
return (CommonViewHolder)convertView.getTag();
}
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 View getmConvertView(){
return mConvertView;
}
public int getmPosition() {
return mPosition;
}}
然后写一个通用的adapter
public abstract class CommonAdapter<T> extends BaseAdapter {
private LayoutInflater mInflater;
private Context mContext;
protected List<T> mDatas;
protected final int mItemLayoutID;
private int mPosition;
public CommonAdapter(Context mContext, List<T> mDatas,int mItemLayoutID) {
this.mContext = mContext;
this.mDatas = mDatas;
this.mItemLayoutID = mItemLayoutID;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getCount() {
return mDatas.size();
}
@Override
public T getItem(int position) {
return mDatas.get(position);
}
public int getmPosition() {
return mPosition;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final CommonViewHolder viewHolder = getViewHolder(position,convertView,parent);
mPosition = position;
convert(viewHolder,getItem(position));
return viewHolder.getmConvertView();
}
protected abstract void convert(CommonViewHolder viewHolder, T item);
private CommonViewHolder getViewHolder(int position,View convertView,ViewGroup parent){
return CommonViewHolder.get(mContext,convertView,parent,mItemLayoutID,position);
}}
调用时
lv_voc.setAdapter(new CommonAdapter<Map<String,Vocabulary>>( getApplicationContext(),list,R.layout.item) {
@Override
protected void convert(CommonViewHolder viewHolder, Map<String, Vocabulary> item) {
TextView voc_name = viewHolder.getView(R.id.item_voc);
Vocabulary bean = list.get(getmPosition()).get("name");
voc_name.setText(bean.name);
}});