I need to add some space to start of the first item and to end of the last item of RecyclerView, so they can scroll to edge of the screen (as they can't with RecyclerView's margin or padding)
The problem is spacing between items should be different, so I can't just add this "space" to item layout. Now I'm trying to add ItemDecoration to my Recycler, but thats what happens:
- Before I even touch it spacing appears letterarily randomly: Random spacing
- Then, when I scroll to the end and go back, required space appears after last item that fits on the screen, not after the last one of my Recycler. The space right after the last item that fits on the screen No space for the real last item
My ItemDecoration class:
public class HorizontalItemDecoration extends RecyclerView.ItemDecoration {
private final int horizontalSpaceWidth;
public HorizontalItemDecoration(int horizontalSpaceWidth) {
this.horizontalSpaceWidth = horizontalSpaceWidth;
}
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, RecyclerView parent,
@NonNull RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) == 0)
outRect.left = horizontalSpaceWidth;
else if (parent.getChildAdapterPosition(view) == parent.getChildCount() - 1)
outRect.right = horizontalSpaceWidth;
}
}
*horizontalSpaceWidth is 16dp, default spacing betsween items is 4dp.
CodePudding user response:
Found the solution by setting LayoutParams to items' parent views. Not the best way I guess, but it works fine for me.
RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
if (position == 0 || position == 14) {
if (position == 0) params.setMargins(spaceWidth, 0, 0, 0);
else params.setMargins(0, 0, spaceWidth, 0);
} else params.setMargins(0, 0, 0, 0);
holder.background.setLayoutParams(params);
*14 is adapter item count - 1
CodePudding user response:
you have to use else for reset the value if position is not 0 or n-1 because views are reusing
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, RecyclerView parent,
@NonNull RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) == 0)
outRect.left = horizontalSpaceWidth;
else if (parent.getChildAdapterPosition(view) == parent.getChildCount() - 1)
outRect.right = horizontalSpaceWidth;
else {
outRect.right = 0;
outRect.left = 0;
}
}