Divide width between two columns in GridLayoutManager

salmanseifian picture salmanseifian · Dec 21, 2017 · Viewed 7.4k times · Source

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?

Answer

Tenten Ponce picture Tenten Ponce · Dec 21, 2017

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