Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GridLayoutManager setSpanSizeLookup not working

I am using GridLayoutManager with 2 cells and for some cells I want span to be one so I tried using setSpanSizeLookup but its not working. I tried returning span count 1 for all positions but still two cells are appearing instead of one.

Following is my code

gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            return 1;
        }
    });
    recyclerView.setLayoutManager(gridLayoutManager);

Any reasons why it is not working?

like image 986
amodkanthe Avatar asked Jan 30 '17 04:01

amodkanthe


2 Answers

Replace

return 1;

to

return 2;

This specify you are spaning 2 cells into 1 cell.

Code

Here is my code for spaning 2 cell for specific position

GridLayoutManager glm=new GridLayoutManager(mContext,2);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            switch(categoryAdapter.getItemViewType(position)) {
                case 1:
                    return 2;
                default:
                    return 1;
            }
        }
    });
    mRecyclerViewCategory.setLayoutManager(glm);

How to define case span in your Recycler Adapter

@Override
public int getItemViewType(int position) {
    if(position==[your_specific_postion_where_to_span]){
        return 1;
    }
    return super.getItemViewType(position);
}
like image 163
Abhishek Singh Avatar answered Sep 23 '22 01:09

Abhishek Singh


i struggled with this as the documentation here is poor at this time. I figured it out like this...

getSpanSize and getSpanIndex seem to work together. For me i was trying to insert a pageViewer inside a gridlayoutManager that spaned two columns. so it was defined like: mGridLayout = new GridLayoutManager(getActivity(), 2);

//must be called before setLayoutManager is invoked
private void setNumOfColumnsForPageViewer(final FallCollectionRecyclerAdapter adapter) {

    mGridLayout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            if (adapter.getItemViewType(position) == MyRecyclerAdapter.TYPE_PAGE_VIEWER)
                return 2; //some other form of item like a header, or whatever you need two spans for
            else
                return 1; //normal item which will take up the normal span you defined in the gridlayoutmanager constructor
        }

        @Override
        public int getSpanIndex(int position, int spanCount) {
            if (adapter.getItemViewType(position) == FallCollectionRecyclerAdapter.TYPE_PAGE_VIEWER)
                return 1;//use a single span
            else
                return 2; //use two spans
        }
    });

    mRecyclerView.setLayoutManager(mGridLayout);
}
like image 42
j2emanue Avatar answered Sep 23 '22 01:09

j2emanue