RecyclerView LayoutManager different span counts on different rows

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)