Set span for items in GridLayoutManager using SpanSizeLookup

Igor Filippov picture Igor Filippov · Nov 11, 2014 · Viewed 52.1k times · Source

I want to implement grid-like layout with section headers. Think of https://github.com/TonicArtos/StickyGridHeaders

What I do now:

mRecyclerView = (RecyclerView) view.findViewById(R.id.grid);
mLayoutManager = new GridLayoutManager(getActivity(), 2);
mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch(mAdapter.getItemViewType(position)){
                    case MyAdapter.TYPE_HEADER:
                        return 1;
                    case MyAdapter.TYPE_ITEM:
                        return 2;
                    default:
                        return -1;
                }
            }
        });

mRecyclerView.setLayoutManager(mLayoutManager);

Now both regular items and headers have span size of 1. How do I solve this?

Answer

Igor Filippov picture Igor Filippov · Nov 13, 2014

The problem was that header should have span size of 2, and regular item should have span size of 1. So correct implementations is:

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