Advertisement
Guest User

Untitled

a guest
Feb 4th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. import android.graphics.Rect;
  2. import android.view.View;
  3.  
  4. import androidx.annotation.NonNull;
  5. import androidx.recyclerview.widget.RecyclerView;
  6.  
  7. public class MarginItemDecoration extends RecyclerView.ItemDecoration {
  8.  
  9.     private final int columnCount;
  10.     private final int margin;
  11.  
  12.     public MarginItemDecoration(int margin, int columnCount) {
  13.         this.columnCount = columnCount;
  14.         this.margin = margin;
  15.     }
  16.  
  17.     @Override
  18.     public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
  19.         super.getItemOffsets(outRect, view, parent, state);
  20.  
  21.         int position = parent.getChildAdapterPosition(view);
  22.  
  23.         boolean firstInRow = position % columnCount == 0;
  24.         boolean lastInRow = position % columnCount == columnCount - 1;
  25.         boolean isInLastRow = position > state.getItemCount() - columnCount - 1;
  26.  
  27.         //top
  28.         outRect.top = margin;
  29.  
  30.         //left
  31.         if (firstInRow) outRect.left = margin;
  32.         else outRect.left = margin / 2;
  33.  
  34.         //right
  35.         if (lastInRow) outRect.right = margin;
  36.         else outRect.right = margin / 2;
  37.  
  38.         //bottom
  39.         if (isInLastRow) outRect.bottom = margin;
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement