Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set full span for GridLayoutManager

I have to create a heterogeneous RecyclerView. The default number of columns is 2, but some items require the full width. I have it while using StaggeredGridLayoutManager like this:

    @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);
        }
    }

How do I do the same thing for GridLayoutManager, where I can easily switch the spans based of different view types?

like image 777
Amit Tiwari Avatar asked Oct 25 '25 09:10

Amit Tiwari


1 Answers

There is a method void setSpanSizeLookup (GridLayoutManager.SpanSizeLookup spanSizeLookup). Use it like this:

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);
like image 61
R. Zagórski Avatar answered Oct 26 '25 23:10

R. Zagórski