Reputation: 423
I know that I can implement a RecyclerView with different views for items on Android.
But my need is a little bit different here. I would like to know how can I implement a RecyclerView with a different number of items by rows.
For example, I would have 2 items for first row, then just 1 item for second row, then 3 items for third row, ...
Is it possible to implement this with a RecyclerView? If so, How can I implement it?
Thanks for your help.
Sylvain
Upvotes: 2
Views: 1310
Reputation: 562
Yes it is possible, you just need to create different Views and get them in the
if (holder instanceof ProfileAdapter.VideoViewHolder) {
} else {
}
and throw the views inside the above method using
public int getItemViewType(int position) {
}
Upvotes: 0
Reputation: 5598
What you're looking for can be done with GridLayoutManager
itself, the only trick here is to use the least common multiple (lcm) of your column counts per row as your total span count. Here is an easy example:
@Override
public void onCreate() {
super.onCreate();
...
int spanCount = lcm(2, 1, 3, 8);
GridLayoutManager layoutManager = new GridLayoutManager(this, spanCount);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
int numberOfColumns;
switch (position) {
case 0:
numberOfColumns = 2;
break;
case 1:
numberOfColumns = 1;
break;
case 2:
numberOfColumns = 3;
break;
case 3:
numberOfColumns = 8;
break;
default:
numberOfColumns = spanCount;
}
return spanCount / numberOfColumns;
}
});
recyclerView.setLayoutManager(layoutManager);
...
}
public static int lcm(int... input) {
int result = input[0];
for(int i = 1; i < input.length; i++) result = lcm(result, input[i]);
return result;
}
Upvotes: 4