StaggeredGridLayoutManager change spanCount dynamically RecyclerView
Asked Answered
L

3

14

How can we change the spanCount of RecyclerView dynamically?

My code create 3 column of cards in RecyclerView:

 StaggeredGridLayoutManager mFavouratesLayoutManager;
 mFavouratesLayoutManager = new StaggeredGridLayoutManager(3,
                StaggeredGridLayoutManager.VERTICAL);

I'm trying to make the adapter like:

  • one element at top row
  • 2 elements in second row
  • 3 items below that
Likable answered 26/12, 2014 at 12:11 Comment(0)
P
12

StaggeredGridLayoutManager does not support that. You can change the span count but it will effect every row. Your only option is to have full rows w/ SGLM.

If you use GridLayoutManager, you can achieve that by setting span count to 6, then providing a SpanSizeLookup that returns

  • 6 for first item
  • 3 for items 1 and 2
  • 2 for items 3 4 5

Etc.

Partlet answered 28/12, 2014 at 17:58 Comment(1)
yes, i tried GridLayoutManager, I was trying to do the same in SGLM.Likable
F
0

You can try this as StaggeredGridLayoutManager does not support that so use Gridlayoutmanager.

GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
    if (position == 1)
        return 6;
    else
        return 2;
}
});
Fionafionna answered 30/1, 2019 at 12:36 Comment(0)
D
0

if your item is not more than 2 span, then you can achieve this with staggeredGridLayoutManager while working with multiple viewtype recyclerview, try initial span count to 2

val staggeredGridLayoutManager = StaggeredGridLayoutManager( 2, // initial span count StaggeredGridLayoutManager.VERTICAL // Orientation )

         binding.recyclerView.layoutManager = staggeredGridLayoutManager

  private fun bindHeader(item: DataModelMyCreate.Header, holder: DataAdapterViewHolder) {
        val staggeredGridLayoutManager =
            holder.itemView.layoutParams as StaggeredGridLayoutManager.LayoutParams
        staggeredGridLayoutManager.isFullSpan = true
        itemView.findViewById<AppCompatTextView>(R.id.tvNameLabel)?.text = item.title
    }

    private fun bindHeaderTwo(
        item: DataModelMyCreate.HeaderTwo,
        holder: DataAdapterViewHolder
    ) {
        val staggeredGridLayoutManager =
            holder.itemView.layoutParams as StaggeredGridLayoutManager.LayoutParams
        staggeredGridLayoutManager.isFullSpan = false
        itemView.findViewById<AppCompatTextView>(R.id.tvNameLabel)?.text = item.title
    }
/////

suppose bindHeader has to show 1 span item count, you should make it isFullSpan = true, while bindHeaderTwo has to show 2 span count, then you have to make it isFullSpan = false.

its working i implemented this

Daves answered 4/10, 2023 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.