Reputation: 1925
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
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
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
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
Etc.
Upvotes: 12