Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set span for items in GridLayoutManager using SpanSizeLookup

People also ask

What is a span in GridLayoutManager?

When creating a recyclerview with a gridlayout layout manager you have to specify the span count in the constructor. Span count refers to the number of columns. This is fairly clunky and doesn't take into account larger screen sizes or screen orientation.


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

Header should have a span equal to the span count of the entire list.

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

Answer to my own question: Override the getSpanSizeLookup() from the Activity after setting the adapter.