Set span for items in GridLayoutManager using SpanSizeLookup

AndroidAndroid Support-LibraryAndroid RecyclerviewGridlayoutmanager

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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

Solution 3 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser468311View Question on Stackoverflow
Solution 1 - Androiduser468311View Answer on Stackoverflow
Solution 2 - AndroidAndroid DeveloperView Answer on Stackoverflow
Solution 3 - AndroidRugved MahamuneView Answer on Stackoverflow