How to display a gridview consisting of rows having varying number of items

I want to display a grid view using recyclerview which displays items in the following format: First row contains one item. Second row contains two items. Third row contains one item. Fourth row contains two items. The format repeats afterwards. A solution will be highly appreciated. :)

Upvotes: 0

Views: 31

Answers (1)

Ajay Shrestha
Ajay Shrestha

Reputation: 2455

Do Like this

private void configureRecyclerView() {
        recyclerView.setHasFixedSize(true);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                // 2 is the sum of items in one row
                switch (position % 2) {
                    case 0:
                        return 2;
                    case 1:
                        return 1;
                }
                throw new IllegalStateException("internal error");
            }
        });


        recyclerView.setLayoutManager(gridLayoutManager);

Upvotes: 1

Related Questions