android listview万能适配器

参考    Android 快速开发系列 打造万能的ListView GridView 适配器     Hongyang

public class CommonViewHolder {

    private Context context;
    private int position;
    private int layoutId;

    private View convertView;
    private SparseArray<View> views;

    private CommonViewHolder(Context context, ViewGroup parent, int layoutId, int position) {
        this.context = context;
        this.layoutId = layoutId;
        this.position = position;
        views = new SparseArray<>();
        convertView = View.inflate(context, layoutId, null);
        convertView.setTag(this);
    }

    public static CommonViewHolder getInstance(Context context, ViewGroup parent, int resId, int position, View convertView) {
        if (convertView == null) {
            return new CommonViewHolder(context, parent, resId, position);
        } else {
            CommonViewHolder holder = (CommonViewHolder) convertView.getTag();
            holder.position = position;
            return holder;
        }
    }

    public int getPosition() { return position;   }

    public View getConvertView() { return convertView;  }

    public <T extends View> T getView(int viewId) {
        View view = views.get(viewId);
        if (view == null) {
            view = this.convertView.findViewById(viewId);
            views.put(viewId, view);
        }
        return (T) view;
    }

    public CommonViewHolder setText(int viewId, String text) {
        ((TextView) getView(viewId)).setText(text);
        return this;
    }

    public CommonViewHolder setImageResource(int viewId, int resId) {
        ((ImageView) getView(viewId)).setImageResource(resId);
        return this;
    }

    public CommonViewHolder setOnClickListener(int viewId, View.OnClickListener onClickListener) {
        getView(viewId).setOnClickListener(onClickListener);
        return this;
    }
}

 

public abstract class CommonAdapter<T> extends BaseAdapter {
    private List<T> datas;
    private Context context;
    private int layoutId;

    public CommonAdapter(Context context, List<T> datas, int layoutId) {
        super();
        this.datas = datas;
        this.context = context;
        this.layoutId = layoutId;
    }

    @Override
    public int getCount() {return datas == null ? 0 : 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) {
        CommonViewHolder holder = CommonViewHolder.getInstance(context, parent, layoutId, position, convertView);
        convert(holder, datas.get(position));
        return holder.getConvertView();
    }

    public abstract void convert(CommonViewHolder holder, T t);
}

 

posted @ 2016-01-07 00:23  MarcoReus  阅读(264)  评论(0编辑  收藏  举报