How to have a GridLayoutManager with header, without changing its adapter?

别说谁变了你拦得住时间么 提交于 2019-12-08 04:52:45

问题


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:


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.



来源:https://stackoverflow.com/questions/33729642/how-to-have-a-gridlayoutmanager-with-header-without-changing-its-adapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!