I used GridLayoutManager
as my layout manger for recycler view.
mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
the result is like below:
but I want to divide width between two columns equally. how can I do that?
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;
}
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With