How to have a GridLayoutManager with header, witho

2019-06-08 11:26发布

Background

I have an app that shows a list of items in a grid-like way, yet not exactly...

The problem

  1. Some of the items have a different height, so the ones near them should gain the same height as they have. This one works on GridLayoutManager.

  2. Some items (actually only the first one in my case) need to span the entire row (which is why I used StaggeredGridLayoutManager ).

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

The question

Is it possible to use StaggeredGridLayoutManager so that when items have different height, it won't make them move in the Y coordinate?

I was thinking: maybe I could use NestedScrollView and GridLayoutManager (because only the first item is spanned), but still, I would like to know if it's possible in the rest of the cases (and also this solution).

1条回答
手持菜刀,她持情操
2楼-- · 2019-06-08 12:15

OK, so I've found a possible solution by still using GridLayoutManager:

  • use getItemViewType and return a specific value for spanned items, and a different value for normal items .

  • Create the needed view in onCreateViewHolder, according to its type, and cast to the needed viewHolder class in onBindViewHolder according to the type.

  • use setSpanSizeLookup, and inside getSpanSize, return the spanned cells in case the type is for such items

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

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

One issue that I have noticed, is that if I try to set the visibility of the header to GONE, it still takes space.

查看更多
登录 后发表回答