Setting span size of single row in StaggeredGridLayoutManager
Solution 1
You can use the setFullSpan method.
In this way the item will layout using all span area.
That means, if orientation is vertical, the view will have full width; if orientation is horizontal, the view will have full height.
Something like this:
public final void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) viewHolder.itemView.getLayoutParams();
layoutParams.setFullSpan(true);
}
Pay attention.
It supports views that span all the columns, but it should be enough for your case.
Solution 2
For anyone using Kotlin.
Using isFullSpan in the onBindViewHolder works.
override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) {
holder.bind(loadState)
val layoutParams = holder.itemView.layoutParams as StaggeredGridLayoutManager.LayoutParams
layoutParams.isFullSpan = true
}
Daniel Julio
Updated on November 04, 2020Comments
-
Daniel Julio over 3 years
I have a staggered grid that has 2 columns. This is working. What I want is at position 0 for the row to span across the 2 columns. I have done this before quite easily using GridLayoutManger as so:
mGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return position == 0 ? 2 : 1; } });
StaggeredGridLayoutManager doesn't provide me with this functionality like GridLayoutManager does.
Is there a different way of doing this? I have searched but not found anyone with the same problem, which is surprising as I would think this functionality would be quite useful for my scenario and for infinite scrolling, when a ProgressBar is shown in the last row of the RecyclerView.
-
Daniel Julio over 8 yearsExactly what I was looking for. Thanks so much Gabriele!
-
Adam Johns about 8 yearsWhat if you want the specific item to span exactly 2 (out of 3) columns? Instead of spanning all columns.
-
Gabriele Mariotti about 8 years@AdamJohns you can't do it with this LayoutManager.
-
Adam Johns about 8 yearsThat's unfortunate. I'm assuming that means no recyclerview layout managers have that capability out of the box.
-
Gabriele Mariotti about 8 years@AdamJohns You can use the GridLayoutManager
-
Daniele Segato almost 8 yearsAn optimization, if all the view of a particular viewType (for example header) are full span you should be set in
onCreateViewHolder()
. If some view is full span and some isn't you have to do it in onBind -
WitaloBenicio over 7 yearsI'm getting a
java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.support.v7.widget.StaggeredGridLayoutManager$LayoutParams
with this method -
Mdlc over 6 years@WitaloBenicio You should ensure that the LayoutManager you have set on your RecyclerView is (or is extending) StaggeredGridLayoutManager