I am trying to add spacing below the last element row in RecyclerView
with GridLayoutManager
. I used custom ItemDecoration
for this purpose with bottom padding when its last element as follows:
public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
private int space;
private int bottomSpace = 0;
public SpaceItemDecoration(int space, int bottomSpace) {
this.space = space;
this.bottomSpace = bottomSpace;
}
public SpaceItemDecoration(int space) {
this.space = space;
this.bottomSpace = 0;
}
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
int childCount = parent.getChildCount();
final int itemPosition = parent.getChildAdapterPosition(view);
final int itemCount = state.getItemCount();
outRect.left = space;
outRect.right = space;
outRect.bottom = space;
outRect.top = space;
if (itemCount > 0 && itemPosition == itemCount - 1) {
outRect.bottom = bottomSpace;
}
}
}
But the problem with this method is that it messed up the element heights in the grid in last row. I am guessing that GridLayoutManager
changes the heights for elements based on spacing left. What is the correct way to achieve this?
This will work correctly for a LinearLayoutManager
. Just in case of a GridLayoutManager
its problematic.
Its very useful in case you have a FAB
in bottom and need items in last row to scroll above FAB
so that they can be visible.
Just add a padding and set
android:clipToPadding="false"
Thanks to this wonderful answer!
What you can do is add an empty footer to your recyclerview. Your padding will be the size of your footer.
You can use the code below to detect first and last rows in a grid view and set top and bottom offsets correspondingly.
With things like this, it's recommended to solve using the ItemDecoration as they are meant for that.
I copied an edited from my original answer here which is actually for equal spacing but it's the same concept.
The solution to this problem lies in overrinding the SpanSizeLookup of GridLayoutManager.
You have to make changes to the GridlayoutManager in the Activity or Fragment where you are inflating the RecylerView.