alexbirkett
alexbirkett

Reputation: 2682

RecyclerView LayoutManager different span counts on different rows

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?

Upvotes: 35

Views: 31466

Answers (2)

Amin Keshavarzian
Amin Keshavarzian

Reputation: 3943

here's how to do it in kotlin:

val layoutManager= GridLayoutManager(activity, 3)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
    override fun getSpanSize(position: Int): Int {
        return when (position) {
            0 -> 3
            else -> 1
        }
    }
}
recyclerView.layoutManager = layoutManager

here, first we have created a grid layout manager with 3 columns, then we have specified the first will occupy the whole 3 columns while the rest take only one.

Upvotes: 10

kris larson
kris larson

Reputation: 30985

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

Upvotes: 69

Related Questions