How to get a GridLayoutManager with a header without changing its adapter?

Background

I have an application that displays a list of elements in a grid, but not exactly ...

Problem

  • Some elements have different heights, so those close to them should have the same height as theirs. This works on the GridLayoutManager.

  • Some elements (actually only the first in my case) should span the entire row (so I used the StaggeredGridLayoutManager).

Using a regular GridLayoutManager, the first requirement worked fine: each row could have a different height. But because of # 2, it actually destroyed # 1.

Question

Is it possible to use the StaggeredGridLayoutManager so that when the elements have different heights, they will not make them move along the Y coordinate?

I thought: maybe I could use NestedScrollView and the GridLayoutManager (because only the first element is stretched), but still I would like to know if this is possible in other cases (as well as this solution).

+1
android android-recyclerview gridlayoutmanager
Nov 16 '15 at 6:33
source share
1 answer

OK, so I found a possible solution, still using the GridLayoutManager:

  • use getItemViewType and return a specific value for composite elements and another value for regular elements,

  • Create the necessary view in onCreateViewHolder according to its type and add the onBindViewHolder class to the necessary viewHolder according to the type.

  • use setSpanSizeLookup , and inside getSpanSize return expanded cells in case the type for such elements

Example:

@Override public int getItemViewType(final int position) { return position==0?VIEW_TYPE_HEADER:VIEW_TYPE_NORMAL; } public ViewHolder onCreateViewHolder(final ViewGroup parent,final int viewType) { if(viewType==VIEW_TYPE_HEADER) ... //create header ViewHolder else ... // create normal item } ... _layoutManager=new GridLayoutManager(...,3,LinearLayoutManager.VERTICAL,false); _layoutManager.setSpanSizeLookup(new SpanSizeLookup() { @Override public int getSpanSize(final int position) { return _adapter.getItemViewType(position)==VIEW_TYPE_HEADER?_layoutManager.getSpanCount():1; } }); 

However, I would like to know how to use the NestedScrollView solution

One of the problems I noticed is that if I try to set the header visibility to GONE, it will still take a space.

0
Nov 16 '15 at 23:04
source share



All Articles