提升RecyclerView开发效率(一)

RecyclerView可以说是越来越强大了,几乎任何复杂界面都可以使用RecyclerView来开发。
即使是并没有重复Section的界面也可以利用RecyclerView来实现Section在多个页面复用和服务端动态控制显示的顺序,或是否显示和隐藏。

这里首先推荐一下Drakeet大神写的开源库,Drakeet现在微软任职。

MultiType

1 声明ViewBinder, 对ViewHolder和数据类进行绑定

class FooViewBinder: ItemViewBinder() {

  override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder {
    return ViewHolder(inflater.inflate(R.layout.item_foo, parent, false))
  }

  override fun onBindViewHolder(holder: ViewHolder, item: Foo) {
    holder.fooView.text = item.value
    Log.d("ItemViewBinder API", "position: ${getPosition(holder)}")
    Log.d("ItemViewBinder API", "items: $adapterItems")
    Log.d("ItemViewBinder API", "adapter: $adapter")
    Log.d("More", "Context: ${holder.itemView.context}")
  }

  class ViewHolder(itemView : View): RecyclerView.ViewHolder(itemView) {
    val fooView: TextView = itemView.findViewById(R.id.foo)
  }
}

2 声明Adapter

    adapter = MultiTypeAdapter()
    adapter.register(TextItemViewBinder())
    adapter.register(ImageItemViewBinder())
    adapter.register(RichItemViewBinder())
    recyclerView.adapter = adapter

此库十分强大,大大节省了我们的开发时间

但是!!!如果你要添加HeaderView或者FooterView的话,的确不太方便。以下引用作者原话:

MultiType 其实本身就支持 HeaderView、FooterView,只要创建一个 Header.class - HeaderViewBinder 和 Footer.class - FooterViewBinder 即可,然后把 new Header() 添加到 items 第一个位置,把 new Footer() 添加到 items 最后一个位置。需要注意的是,如果使用了 Footer View,在底部插入数据的时候,需要添加到 最后位置 - 1,即倒二个位置,或者把 Footer remove 掉,再添加数据,最后再插入一个新的 Footer.

是不是有点麻烦?!

另外还有个坑,如果你同时使用MultiType和其他第三方RecyclerView库的话,也很可能会出错。
对于有添加header、foot 的recyclerview,会报错

和XRecyclerView搭配是有问题的,XRecyclerView的下拉刷新和加载更多的实现是通过添加HeadView和FootView实现的,但是没有在MultiType中处理这些HeadView和FootView,就会有上面的问题。不想用swiperefreshlayout的话,需要修改XRecyclerView的代码,不过还没想好怎么修改。

我来说以下自己的解决方案,首先我们不要重复造轮子,有这样一个第三方开源库: Smart-HeaderFooter-RecyclerView,他可以很方便的给RecyclerView添加Header和Footer,但是同样不能直接和MultiType库一起使用。

下面我们来改造一下Smart-HeaderFooter-RecyclerView,让他可以支持MultiType。直接上代码:

public class RecyclerViewAdapterWrapper extends RecyclerView.Adapter {

    protected final RecyclerView.Adapter wrapped;

    public RecyclerViewAdapterWrapper(RecyclerView.Adapter wrapped) {
        super();
        this.wrapped = wrapped;
        this.wrapped.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            public void onChanged() {
                notifyDataSetChanged();
            }

            public void onItemRangeChanged(int positionStart, int itemCount) {
                notifyItemRangeChanged(positionStart, itemCount);
            }

            public void onItemRangeInserted(int positionStart, int itemCount) {
                notifyItemRangeInserted(positionStart, itemCount);
            }

            public void onItemRangeRemoved(int positionStart, int itemCount) {
                notifyItemRangeRemoved(positionStart, itemCount);
            }

            public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
                notifyItemMoved(fromPosition, toPosition);
            }
        });
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return wrapped.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        wrapped.onBindViewHolder(holder, position);
    }

    @Override
    public int getItemCount() {
        return wrapped.getItemCount();
    }

    @Override
    public int getItemViewType(int position) {
        return wrapped.getItemViewType(position);
    }

    @Override
    public void setHasStableIds(boolean hasStableIds) {
        wrapped.setHasStableIds(hasStableIds);
    }

    @Override
    public long getItemId(int position) {
        return wrapped.getItemId(position);
    }

    @Override
    public void registerAdapterDataObserver(RecyclerView.AdapterDataObserver observer) {
        wrapped.registerAdapterDataObserver(observer);
    }

    @Override
    public void unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver observer) {
        wrapped.unregisterAdapterDataObserver(observer);
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        wrapped.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        wrapped.onDetachedFromRecyclerView(recyclerView);
    }

    public RecyclerView.Adapter getWrappedAdapter() {
        return wrapped;
    }
}
public class HeaderAndFooterAdapterWrapper extends RecyclerViewAdapterWrapper {
    public static final int TYPE_HEADER = -1;
    public static final int TYPE_FOOTER = -2;

    private RecyclerView.LayoutManager layoutManager;

    private View headerView, footerView;

    public HeaderAndFooterAdapterWrapper(@NonNull RecyclerView.Adapter targetAdapter) {
        super(targetAdapter);
    }

    public void setHeaderView(View view) {
        headerView = view;
        getWrappedAdapter().notifyDataSetChanged();
    }

    public void removeHeaderView() {
        headerView = null;
        getWrappedAdapter().notifyDataSetChanged();
    }

    public void setFooterView(View view) {
        footerView = view;
        getWrappedAdapter().notifyDataSetChanged();
    }

    public void removeFooterView() {
        footerView = null;
        getWrappedAdapter().notifyDataSetChanged();
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        layoutManager = recyclerView.getLayoutManager();
        setGridHeaderFooter(layoutManager);
    }

    @Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        if (isHeaderView(holder) || isFooterView(holder)) {
            super.onViewRecycled(holder);
            return;
        }
        wrapped.onViewRecycled(holder);
    }

    @Override
    public boolean onFailedToRecycleView(RecyclerView.ViewHolder holder) {
        if (isHeaderView(holder) || isFooterView(holder)) {
            return super.onFailedToRecycleView(holder);
        }
        return wrapped.onFailedToRecycleView(holder);
    }

    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        if (isHeaderView(holder) || isFooterView(holder)) {
            super.onViewAttachedToWindow(holder);
            return;
        }
        wrapped.onViewAttachedToWindow(holder);
    }

    @Override
    public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
        if (isHeaderView(holder) || isFooterView(holder)) {
            super.onViewDetachedFromWindow(holder);
            return;
        }
        wrapped.onViewDetachedFromWindow(holder);
    }

    @Override
    public int getItemCount() {
        return super.getItemCount() + (hasHeader() ? 1 : 0) + (hasFooter() ? 1 : 0);
    }

    @Override
    public int getItemViewType(int position) {
        if (hasHeader() && position == 0) {
            return TYPE_HEADER;
        }

        if (hasFooter() && position == getItemCount() - 1) {
            return TYPE_FOOTER;
        }
        return super.getItemViewType(hasHeader() ? position - 1 : position);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = null;
        if (viewType == TYPE_HEADER) {
            itemView = headerView;
        } else if (viewType == TYPE_FOOTER) {
            itemView = footerView;
        }
        if (itemView != null) {
            //set StaggeredGridLayoutManager header & footer view
            if (layoutManager instanceof StaggeredGridLayoutManager) {
                ViewGroup.LayoutParams targetParams = itemView.getLayoutParams();
                StaggeredGridLayoutManager.LayoutParams StaggerLayoutParams;
                if (targetParams != null) {
                    StaggerLayoutParams = new StaggeredGridLayoutManager.LayoutParams(targetParams.width, targetParams.height);
                } else {
                    StaggerLayoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                }
                StaggerLayoutParams.setFullSpan(true);
                itemView.setLayoutParams(StaggerLayoutParams);
            }
            return new RecyclerView.ViewHolder(itemView) {
            };
        }
        return super.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == TYPE_HEADER || getItemViewType(position) == TYPE_FOOTER) {
            //if you need get header & footer state , do here
            return;
        }
        super.onBindViewHolder(holder, hasHeader() ? position - 1 : position);
    }

    private void setGridHeaderFooter(RecyclerView.LayoutManager layoutManager) {
        if (layoutManager instanceof GridLayoutManager) {
            final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    boolean isShowHeader = (position == 0 && hasHeader());
                    boolean isShowFooter = (position == getItemCount() - 1 && hasFooter());
                    if (isShowFooter || isShowHeader) {
                        return gridLayoutManager.getSpanCount();
                    }
                    return 1;
                }
            });
        }
    }

    private boolean hasHeader() {
        return headerView != null;
    }

    private boolean hasFooter() {
        return footerView != null;
    }

    private boolean isHeaderView(RecyclerView.ViewHolder holder) {
        return holder.getItemViewType() == TYPE_HEADER;
    }

    private boolean isFooterView(RecyclerView.ViewHolder holder) {
        return holder.getItemViewType() == TYPE_FOOTER;
    }
}

因为MultiType的作者Drakeet大神推荐使用组合的模式,而不是依赖继承(一看就是熟读Effective java的,对此我也是深表认同),所以我们创建的两个类就是对目标Adapter的各种包装,各种转发。

好了,怎么使用呢?

        var smartRecyclerAdapter = HeaderAndFooterAdapterWrapper(multiTypeAdapter)
        smartRecyclerAdapter.setHeaderView(headerView)
        smartRecyclerAdapter.setFooterView(footerView)
        ptrRecyclerView.adapter = smartRecyclerAdapter

嗯,以后就可以轻松愉快的添加Header和Footer了。

你可能感兴趣的:(提升RecyclerView开发效率(一))