I want a RecyclerView.LayoutManager
that allows me to specify different span counts for different rows as a repeating pattern. For example 2,3 with 10 items would look like this:
------------- | | | | | | ------------- | | | | | | | | ------------- | | | | | | ------------- | | | | | | | | -------------
I can think of a way to hack this with GridLayoutManager
and SpanSizeLookup
but has anybody come up with a cleaner way to do this?
When creating a recyclerview with a gridlayout layout manager you have to specify the span count in the constructor. Span count refers to the number of columns. This is fairly clunky and doesn't take into account larger screen sizes or screen orientation.
In order to use RecyclerView for creating staggering grid views, we need to use StaggeredGridLayoutManager. LayoutManager is responsible for measuring and positioning item views in the RecyclerView and also recycle the item views when they are no longer visible to the user.
This wear-specific implementation of LinearLayoutManager provides basic offsetting logic for updating child layout. A LayoutManager is responsible for measuring and positioning item views within a RecyclerView as well as determining the policy for when to recycle item views that are no longer visible to the user.
To do what you want, you probably have to write your own LayoutManager
.
I think this is easier:
// Create a grid layout with 6 columns // (least common multiple of 2 and 3) GridLayoutManager layoutManager = new GridLayoutManager(this, 6); layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { // 5 is the sum of items in one repeated section switch (position % 5) { // first two items span 3 columns each case 0: case 1: return 3; // next 3 items span 2 columns each case 2: case 3: case 4: return 2; } throw new IllegalStateException("internal error"); } });
If your grid item needs to know its span size, you can find it like this within ViewHolder
:
// this line can return null when the view hasn't been added to the RecyclerView yet RecyclerView recyclerView = (RecyclerView) itemView.getParent(); GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager(); int spanSize = gridLayoutManager.getSpanSizeLookup().getSpanSize(getLayoutPosition());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With