Skip to content

Commit 0c95c41

Browse files
Added RecyclerViewVerticalGapItemDecoration.
1 parent 2902fa7 commit 0c95c41

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.tazkiyatech.utils.views;
2+
3+
import android.graphics.Rect;
4+
import android.view.View;
5+
6+
import androidx.annotation.NonNull;
7+
import androidx.recyclerview.widget.RecyclerView;
8+
9+
/**
10+
* An extension of {@link RecyclerView.ItemDecoration} that
11+
* draws a vertical gap between each item in a {@link RecyclerView}.
12+
* <p>
13+
* Unlike the {@link androidx.recyclerview.widget.DividerItemDecoration} class offered by the
14+
* <a href="https://maven.google.com/web/index.html#androidx.recyclerview:recyclerview">recyclerview</a>
15+
* library, this class does not draw a vertical gap under the final item in the {@link RecyclerView}.
16+
* <p>
17+
* See <a href="https://stackoverflow.com/a/27037230/1071320">this answer</a> in Stack Overflow
18+
* for a better understanding of {@link RecyclerView.ItemDecoration}.
19+
*/
20+
public class RecyclerViewVerticalGapItemDecoration extends RecyclerView.ItemDecoration {
21+
22+
private final int verticalGapInPixels;
23+
24+
/**
25+
* Constructor.
26+
*
27+
* @param verticalGapInPixels The height of the vertical gap (in pixels).
28+
*/
29+
public RecyclerViewVerticalGapItemDecoration(int verticalGapInPixels) {
30+
this.verticalGapInPixels = verticalGapInPixels;
31+
}
32+
33+
@Override
34+
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
35+
RecyclerView.Adapter<?> adapter = parent.getAdapter();
36+
int itemCount = adapter != null ? adapter.getItemCount() : 0;
37+
38+
int itemPosition = parent.getChildLayoutPosition(view);
39+
40+
if (itemPosition + 1 < itemCount) {
41+
outRect.set(0, 0, 0, verticalGapInPixels);
42+
} else { // this is the last item in the RecyclerView so don't add vertical space underneath it
43+
outRect.set(0, 0, 0, 0);
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)