Search code examples
javaandroidandroid-recyclerviewgrid-layout

How do you center a gridlayout horizontally using recyclerview?


I am trying to center a gridlayout using recycler view.

The code listed below is what I have attempted but it and messed around with, but wasn't really understanding how it worked.

The icons show up something similar to below.

  1. i ..i
  2. i..i..i
  3. i..i..i

I want

  1. ..i.i
  2. i..i..i
  3. i..i..i
 GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 6, RecyclerView.VERTICAL, true);
        final int totalSize = Cards.size();
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int span;
                span = totalSize % 3;
                if (totalSize < 3) {
                    return 6;
                } else if (span == 0 || (position <= ((totalSize - 1) - span))) {
                    return 2;
                } else if (span == 1) {
                    return 6;
                } else {
                    return 3;
                }
            }
        });
        recyclerView.setLayoutManager(gridLayoutManager);

Solution


  • The integer that you return in getSpanSize specifies the number of columns width a certain cell should occupy. From your code, you seem to need most of the elements to occupy one third of the layout width

         (position <= ((totalSize - 1) - span))
    

    That code returns true for most of the cases, except for the last few cells. I think the code that you have written is flawed, and I cannot understand what you exactly need. If you have a picture that you can share, it would greatly help in getting help for your solution.