Search code examples
javaandroidrecyclerview-layoutstaggeredgridlayoutmanager

Change column span count of StaggeredGridLayout dynamically based on item position


I would like to achieve this layout for (n) items list: this layout

So far now I'm able to display the items in two columns but how can I merge two columns in one for specific position (i.e as item 7)?

I have tried many solution provided at SO and also other but none of them worked for me. The solutions provided there were either using LinearLayout inflating static layouts or were providing solution for partition with in the columns.

I've also tried using setSpanLookup method but no luck..


Solution

  • Finally the solution that worked for me after exhaustive struggle is here:

        @Override
            public void onViewAttachedToWindow(MyViewHolder holder) {
                super.onViewAttachedToWindow(holder);
                ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
                if(lp != null
                        && lp instanceof StaggeredGridLayoutManager.LayoutParams
                        && (holder.getLayoutPosition() == 6 || holder.getLayoutPosition() == 13)) {
                    StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
                    p.setFullSpan(true);
                }
               holder.setIsRecyclable(false);
            }
    

    Hope this will help u also.