Bora
Bora

Reputation: 1925

StaggeredGridLayoutManager change spanCount dynamically RecyclerView

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:

Upvotes: 14

Views: 7729

Answers (3)

Jasim 9D
Jasim 9D

Reputation: 1

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

Upvotes: 0

Shubham Ratawa
Shubham Ratawa

Reputation: 126

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

Upvotes: 0

yigit
yigit

Reputation: 38253

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.

Upvotes: 12

Related Questions