Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide width between two columns in GridLayoutManager

I used GridLayoutManager as my layout manger for recycler view.

  mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));

the result is like below: enter image description here

but I want to divide width between two columns equally. how can I do that?

like image 323
salmanseifian Avatar asked Dec 21 '17 07:12

salmanseifian


2 Answers

Try adding this on your recyclerView:

mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int spanCount = 2;
            int spacing = 10;//spacing between views in grid

            if (position >= 0) {
                int column = position % spanCount; // item column

                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = 0;
                outRect.right = 0;
                outRect.top = 0;
                outRect.bottom = 0;
            }
        }
    });
like image 122
Tenten Ponce Avatar answered Sep 27 '22 17:09

Tenten Ponce


Setting the column count like you do:

mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));

... actually makes the grid splitting into columns of the same width.

This suggests that the problem lies somewhere else, probably in the item layout. I suppose that some whitespaces (paddings/margins) are responsible for the fact that the items are shifted to the right. Try to remove these spacings and check if it works.

If it helps, you can always add new spacing with ItemDecoration but it isn't the reason for the incorrect size of your columns.

I think that turning on Show Layout Bounds option may be helpful for you.

like image 37
paulina_glab Avatar answered Sep 27 '22 18:09

paulina_glab