封装RecycleView 多类型Item

本文参考:
http://blog.csdn.net/u014315849/article/details/52537700
http://blog.csdn.net/lmj623565791/article/details/45059587
http://blog.csdn.net/lmj623565791/article/details/51118836

Recycleview设置:

1.setLayoutManager() //设置布局管理器
2.setAdapter() //设置适配器
3.addItemDecoration() //添加装饰(如分割线)
4.setItemAnimator() //设置动画(如添加、删除动画)

RecyclerView.LayoutManager是一个抽象类

实现类:
1.LinearLayoutManager 线性管理器,支持横向、纵向。
2.GridLayoutManager 网格布局管理器
3.StaggeredGridLayoutManager 瀑布流式布局管理器

ViewHolder

ViewHolder是google在优化ListView性能的技巧上就提到的,虽然google并没有强制使用,但事实上它已经成为ListView的编写规范。在RecyclerView上,ViewHolder的使用成为了一种强制手段了。
首先来看看ViewHolder的用法,这是一个简单的获取String数组并展现到TextView上。通过数组的大小来创建item的数量。

public class MyAdapter extends RecyclerView.Adapter {
    public String[] datas = null;
    public MyAdapter(String[] datas) {
        this.datas = datas;
    }
    //创建新View,被LayoutManager所调用
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
        ViewHolder vh = new ViewHolder(view);
        return vh;
    }
    //将数据与界面进行绑定的操作
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {
        viewHolder.mTextView.setText(datas[position]);
    }
    //获取数据的数量
    @Override
    public int getItemCount() {
        return datas.length;
    }
    //自定义的ViewHolder,持有每个Item的的所有界面元素
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextView;
        public ViewHolder(View view){
        super(view);
            mTextView = (TextView) view.findViewById(R.id.text);
        }
    }
}

介绍完RecycleView和ViewHolder,接下来我们看一下封装目录(参考鸿洋大神的github项目)

封装RecycleView 多类型Item_第1张图片
文件目录

一、封装ViewHolder

public class BaseViewHolder extends RecyclerView.ViewHolder {

    //类似HashMap Android用SparseArray性能更高
    //管理view
    private SparseArray mViews;
    //学习过ListView性能优化的肯定知道 这是缓存视图的
    private View mConvertView;
    private Context mContext;

    public BaseViewHolder(Context context, View itemView) {
        super(itemView);
        mContext = context;
        mConvertView = itemView;
        mViews = new SparseArray<>();
    }

    public static BaseViewHolder createViewHolder(Context context, View itemView) {
        return new BaseViewHolder(context, itemView);
    }

    public static BaseViewHolder createViewHolder(Context context,
                                              ViewGroup parent, int layoutId) {
        View itemView = LayoutInflater.from(context).inflate(layoutId, parent,
                false);
        return new BaseViewHolder(context, itemView);
    }

    /**
     * 通过ViewId获取控件
     * @author dyb
     * @createTime 2017/3/17 22:54
     */
    public  T getView(int viewId)
    {
        //先去SparseArray取view
        View view = mViews.get(viewId);//viewId 指的是 R.id.XXX这种 对应一个viewId
        if (view == null)
        {
            view = mConvertView.findViewById(viewId);//SparseArray中没有 则到convertView中直接findViewById
            mViews.put(viewId, view);//把view放进SparseArray中
        }
        return (T) view;
    }

    public View getConvertView() {
        return mConvertView;
    }

    //以下为辅助方法(可略看)

    //设置TextView内容
    public BaseViewHolder setText(int viewId, String text) {
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }

    //设置ImageView资源
    public BaseViewHolder setImageResource(int viewId, int resId) {
        ImageView view = getView(viewId);
        view.setImageResource(resId);
        return this;
    }

    //设置ImageView图片Url
    public BaseViewHolder setImageUrl(int viewId, String imgUrl) {
        ImageView view = getView(viewId);
        Glide.with(view.getContext())
                .load(imgUrl)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.drawable.v)//设置加载中图片
                .error(R.drawable.v)//设置加载失败图片
                .crossFade()//淡入淡出
                .fitCenter()//等比例拉伸填满ImageView
                .into(view);
        return this;
    }

    //设置ImageView图片Bitmap
    public BaseViewHolder setImageBitmap(int viewId, Bitmap bitmap) {
        ImageView view = getView(viewId);
        view.setImageBitmap(bitmap);
        return this;
    }

    //设置ImageView图片Drawable
    public BaseViewHolder setImageDrawable(int viewId, Drawable drawable) {
        ImageView view = getView(viewId);
        view.setImageDrawable(drawable);
        return this;
    }

    //事件监听
    public BaseViewHolder setOnClickListener(int viewId,
                                         View.OnClickListener listener) {
        View view = getView(viewId);
        view.setOnClickListener(listener);
        return this;
    }

看一下BaseViewHolder完成的工作:

持有itemView 向外提供getViewByViewId方法

持有itemView:

由构造器传入itemView
或者传入Context context,ViewGroup parent, int layoutId 调用LayoutInflater.from(context).inflate(layoutId, parent,false);生成itemView

向外提供getViewByViewId方法:

传入viewId去获取itemView具体的childrenView(findViewById)
为了提高效率 采用 SparesArray映射存储

二、封装MultiItemTypeAdapter(多类型item适配器)

你可能会问为什么不先封装SingleItemTypeAdapter(单类型item适配器)
实际上SingleItemTypeAdapter是MultiItemTypeAdapter的特例,只要对MultiItemTypeAdapter进行限定就能实现。

public class MultiItemTypeAdapter extends RecyclerView.Adapter {

    protected Context mContext;
    protected List mDatas;

    protected ItemViewDelegateManager mItemViewDelegateManager;
    protected OnItemClickListener mOnItemClickListener;
    public int offset = 0;

    public MultiItemTypeAdapter(Context context, List datas) {
        mContext = context;
        mDatas = datas;
        mItemViewDelegateManager = new ItemViewDelegateManager();
    }

    public MultiItemTypeAdapter(Context context) {
        this(context, new ArrayList());
    }

    @Override
    public int getItemViewType(int position) {
        if (!useItemViewDelegateManager())
            return super.getItemViewType(position);
        return mItemViewDelegateManager.getItemViewType(mDatas.get(position), position);
    }


    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        int layoutId = mItemViewDelegateManager.getItemViewLayoutId(viewType);
        BaseViewHolder holder = BaseViewHolder.createViewHolder(mContext, parent, layoutId);
        setListener(parent, holder, viewType);
        return holder;
    }

    public void convert(BaseViewHolder holder, T t) {
        mItemViewDelegateManager.convert(holder, t, holder.getAdapterPosition());
    }

    protected boolean isEnabled(int viewType) {
        return true;
    }


    protected void setListener(final ViewGroup parent, final BaseViewHolder viewHolder, int
            viewType) {
        if (!isEnabled(viewType))
            return;
        viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnItemClickListener != null) {
                    int position = viewHolder.getAdapterPosition();
                    mOnItemClickListener.onItemClick(v, viewHolder, mDatas.get(position - offset)
                            , position);
                }
            }
        });

        viewHolder.getConvertView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (mOnItemClickListener != null) {
                    int position = viewHolder.getAdapterPosition();
                    return mOnItemClickListener.onItemLongClick(v, viewHolder, mDatas.get
                            (position - offset), position);
                }
                return false;
            }
        });
    }

    //将数据与界面进行绑定的操作
    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        convert(holder, mDatas.get(position));
    }

    //获取数据的数量
    @Override
    public int getItemCount() {
        int itemCount = mDatas.size();
        return itemCount;
    }


    public List getDatas() {
        return mDatas;
    }

    public MultiItemTypeAdapter addItemViewDelegate(ItemViewDelegate itemViewDelegate) {
        mItemViewDelegateManager.addDelegate(itemViewDelegate);
        return this;
    }

    public MultiItemTypeAdapter addItemViewDelegate(int viewType, ItemViewDelegate
            itemViewDelegate) {
        mItemViewDelegateManager.addDelegate(viewType, itemViewDelegate);
        return this;
    }

    protected boolean useItemViewDelegateManager() {
        return mItemViewDelegateManager.getItemViewDelegateCount() > 0;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, RecyclerView.ViewHolder holder, T o, int position);

        boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, T o, int position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.mOnItemClickListener = onItemClickListener;
    }

    public void addDataAll(List data) {
        mDatas.addAll(data);
    }

    public void clearData() {
        mDatas.clear();
    }
}

public class ItemViewDelegateManager {

    SparseArrayCompat> delegates = new SparseArrayCompat();

    public int getItemViewDelegateCount() {
        return delegates.size();
    }

    public ItemViewDelegateManager addDelegate(ItemViewDelegate delegate) {
        int viewType = delegates.size();
        if (delegate != null) {
            delegates.put(viewType, delegate);
            viewType++;
        }
        return this;
    }

    public ItemViewDelegateManager addDelegate(int viewType, ItemViewDelegate delegate) {
        if (delegates.get(viewType) != null) {
            throw new IllegalArgumentException("An ItemViewDelegate is already registered for the" +
                    " viewType = " + viewType + ". Already registered ItemViewDelegate is " +
                    delegates
                    .get(viewType));
        }
        delegates.put(viewType, delegate);
        return this;
    }

    public ItemViewDelegateManager removeDelegate(ItemViewDelegate delegate) {
        if (delegate == null) {
            throw new NullPointerException("ItemViewDelegate is null");
        }
        int indexToRemove = delegates.indexOfValue(delegate);

        if (indexToRemove >= 0) {
            delegates.removeAt(indexToRemove);
        }
        return this;
    }

    public ItemViewDelegateManager removeDelegate(int itemType) {
        int indexToRemove = delegates.indexOfKey(itemType);

        if (indexToRemove >= 0) {
            delegates.removeAt(indexToRemove);
        }
        return this;
    }

    public int getItemViewType(T item, int position) {
        int delegatesCount = delegates.size();
        for (int i = delegatesCount - 1; i >= 0; i--) {
            ItemViewDelegate delegate = delegates.valueAt(i);
            if (delegate.isForViewType(item, position)) {
                return delegates.keyAt(i);
            }
        }
        throw new IllegalArgumentException("No ItemViewDelegate added that matches position=" +
                position + " in data source");
    }

    public void convert(BaseViewHolder holder, T item, int position) {
        int delegatesCount = delegates.size();
        for (int i = 0; i < delegatesCount; i++) {
            ItemViewDelegate delegate = delegates.valueAt(i);

            if (delegate.isForViewType(item, position)) {
                delegate.convert(holder, item, position);
                return;
            }
        }
        throw new IllegalArgumentException("No ItemViewDelegateManager added that matches " +
                "position=" + position + " in data source");
    }


    public int getItemViewLayoutId(int viewType) {
        return delegates.get(viewType).getItemViewLayoutId();
    }

    public int getItemViewType(ItemViewDelegate itemViewDelegate) {
        return delegates.indexOfValue(itemViewDelegate);
    }
}
public interface ItemViewDelegate {
    //向 Adapter 提供布局文件的 id 
    int getItemViewLayoutId();
    
    //判断传入的 item 是不是自己应该处理的类型 
    boolean isForViewType(T item, int position);
    
    //绑定 holder 和数据
    void convert(BaseViewHolder holder, T t, int position);
}

重点:

一个item对应一个ItemViewDelegate接口 实现

//向 Adapter 提供布局文件的 id
//判断传入的 item 是不是自己应该处理的类型
//绑定 holder 和数据

ItemViewDelegateManager 管理ItemViewDelegate

用到了SparseArrayCompat来管理ItemViewDelegate

SparseArrayCompat其实是一个map容器,它使用了一套算法优化了hashMap,可以节省至少50%的缓存.
缺点但是有局限性只针对下面类型.
key: Integer; value: object
因此当HshMap()的key是Integer类型时推荐使用SparseArrayCompat(),用法与Map相似.

重点看这个数据绑定的逻辑

在数据绑定时遍历SparseArrayCompat中的ItemViewDelegate
根据ItemViewDelegate实现的isForViewType(item, position)方法
来判断是否由当前ItemViewDelegate来处理数据绑定

封装RecycleView 多类型Item_第2张图片
Paste_Image.png

三、封装SingleItemTypeAdapter

上面也说过了SingleItemTypeAdapter的实现只要对MultiItemTypeAdapter进行一些限定:
getItemViewLayoutId 限定为一种layoutId
isForViewType 永远返回true
convert 数据绑定还是交由具体子类去实现
public abstract class SingleItemTypeAdapter extends MultiItemTypeAdapter {

    protected Context mContext;
    protected int mLayoutId;
    protected List mDatas;
    protected LayoutInflater mInflater;

    public SingleItemTypeAdapter(final Context context, final int layoutId) {
        this(context, layoutId, new ArrayList());
    }

    public SingleItemTypeAdapter(final Context context, final int layoutId, List datas) {
        super(context, datas);
        mContext = context;
        mInflater = LayoutInflater.from(context);
        mLayoutId = layoutId;
        mDatas = datas;

        addItemViewDelegate(new ItemViewDelegate() {
            @Override
            public int getItemViewLayoutId() {
                return layoutId;
            }

            @Override
            public boolean isForViewType(T item, int position) {
                return true;
            }

            @Override
            public void convert(BaseViewHolder holder, T t, int position) {
                SingleItemTypeAdapter.this.convert(holder, t, position);
            }
        });
    }

    protected abstract void convert(BaseViewHolder holder, T t, int position);
}

你可能感兴趣的:(封装RecycleView 多类型Item)