封装commonAdapter类

定义一个CommonViewHolder类

public abstract class CommonViewHolder{ //实现实例化控件 public abstract void initView(View view); //实现对控件进行填充内容 public abstract void updateView(int pos, T item); }

定义一个CommonAdapter类:
public abstract class CommonAdapter extends BaseAdapter{protected Context mContext; protected List mList; /** * 构造函数传入上下文和数据 * @param mContext * @param mList */ public CommonAdapter(Context mContext, List mList) { this.mContext = mContext; this.mList = mList; }@Override public int getCount() { return mList.size(); }@Override public Object getItem(int position) { return mList.get(position); }@Override public long getItemId(int position) { return position; }@Override public View getView(int position, View convertView, ViewGroup parent) { //定义holder对象 CommonViewHolder holder; if (convertView == null){ //解析布局文件为view convertView = LayoutInflater.from(mContext).inflate(getLayout(), parent,false); //创建holder对象 holder = createViewHolder(); //初始化控件 holder.initView(convertView); //保存holder对象 convertView.setTag(holder); } else { holder = (CommonViewHolder) convertView.getTag(); } //更新控件中的内容 holder.updateView(position, getItem(position)); return convertView; }//交给子类实现创建holder对象 protected abstract CommonViewHolder createViewHolder(); //交给子类获取到布局文件 protected abstract int getLayout(); }

具体实现类:
public class MyWordAdapter extends CommonAdapter { public MyWordAdapter(Context mContext, List mList) { super(mContext, mList); }//实现创建viewHolder对象 @Override protected CommonViewHolder createViewHolder() { return new ViewHolder(); }//返回布局文件 @Override protected int getLayout() { return R.layout.my_word_layout; }//继承CommonViewHolder,实现具体的初始化工作和更新UI private class ViewHolder extends CommonViewHolder{ private TextView text_key; private TextView text_value; @Override public void initView(View view) { text_key = (TextView) view.findViewById(R.id.id_text_word_layout_key); text_value = https://www.it610.com/article/(TextView) view.findViewById(R.id.id_text_word_layout_value); }@Override public void updateView(int pos, WordBean item) { text_key.setText(item.getKey()); text_value.setText(item.getValue()); } }}

    推荐阅读