为GridLayoutManager设置完整范围

时间:2016-10-27 11:18:55

标签: android android-recyclerview gridlayoutmanager

我必须创建异构RecyclerView。默认列数为2,但某些项目需要全宽。我在使用StaggeredGridLayoutManager这样的时候就可以了:

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        int viewType = getItemViewType(position);
        FeedItems currentItem = getItem(position);
        StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
        switch (viewType) {
            case ITEM_TYPE_HEADER:
                final HeaderItem headerItem = currentItem.getHeaderItem();
                layoutParams.setFullSpan(true);
        }
    }

如何为GridLayoutManager做同样的事情,我可以根据不同的视图类型轻松切换范围?

1 个答案:

答案 0 :(得分:6)

有一种方法void setSpanSizeLookup (GridLayoutManager.SpanSizeLookup spanSizeLookup)。像这样使用它:

mLayoutManager = new GridLayoutManager(getActivity(), 2);
mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            switch(mAdapter.getItemViewType(position)){
                case 1:
                    return 1;
                case 2:
                    return 2;
                default:
                    return -1;
            }
        }
    });

mRecyclerView.setLayoutManager(mLayoutManager);