Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce space between columns in recycler view(GridLayoutManager) in android

I am using GridLayoutManager of recyclerview to display custom gallery in my app. I have implementated all the features like gallery. But there is a small thing Im stuck with. In one row I have 3 images. But I need to reduce the space between the images. While doing so , I dont want to show more than 3 images in a row, but the image size (if needed) can increase.

like image 764
D Agrawal Avatar asked Oct 19 '25 11:10

D Agrawal


1 Answers

You can use custom RecyclerViewItemDecorator:

public class RecyclerViewItemDecorator extends RecyclerView.ItemDecoration {
  private int spaceInPixels;

  public RecyclerViewItemDecorator(int spaceInPixels) {
    this.spaceInPixels = spaceInPixels;
  }

  @Override
  public void getItemOffsets(Rect outRect, View view, 
      RecyclerView parent, RecyclerView.State state) {
    outRect.left = spaceInPixels;
    outRect.right = spaceInPixels;
    outRect.bottom = spaceInPixels;

    if (parent.getChildLayoutPosition(view) == 0) {
        outRect.top = spaceInPixels;
    } else {
        outRect.top = 0;
    }
  }
}

Then add it to your RecyclerView:

// For example 10 pixels
int spaceInPixels = 10;
mRecyclerView.addItemDecoration(new RecyclerViewItemDecorator(spaceInPixels));

Hope it helps!

like image 171
Ivan Ivanov Avatar answered Oct 21 '25 02:10

Ivan Ivanov