1

I am trying to implement a snapping mechanism for my horizontal recyclerView and i am using this code to do it.

But there seems to be some space between all my child items. Please see screenshot below (I'm not allowed to embed images yet, so please check the link):

enter image description here

I'm not sure why there is spacing between my child items. I fifured it has something to do with this code below:

private void setMarginsForChild(View child) {
    int lastItemIndex = getLayoutManager().getItemCount() - 1;
    int childIndex = getChildPosition(child);
    if(childIndex != -1) ((SampleAdapter)getAdapter()).setSelection(childIndex);
    int startMargin = childIndex == 0 ? getMeasuredWidth() / 2 : getMeasuredWidth() / 2;
    int endMargin = childIndex == lastItemIndex ? getMeasuredWidth() / 2 : getMeasuredWidth() / 2;

    //RTL works for API 17+
    if (ViewCompat.getLayoutDirection(child) == ViewCompat.LAYOUT_DIRECTION_RTL) {
        // The view has RTL layout
        ((ViewGroup.MarginLayoutParams) child.getLayoutParams()).setMargins(endMargin, 0, startMargin, 0);
    } else {
        // The view has LTR layout
        ((ViewGroup.MarginLayoutParams) child.getLayoutParams()).setMargins(startMargin, 0, endMargin, 0);
    }
    child.requestLayout();
}

But if I don't set margin to child items, the recyclerView items do not snap to the center of the screen. Could someone help point me in the right direction?

Piyush Gupta
  • 2,181
  • 3
  • 13
  • 28

2 Answers2

0

So I got it working using this code. It is a custom ScrollListener that can be used to snap a list item to the center after scroll. Just in case anyone faces this problem in the future

0

there is another option layoutmanagers and in particular SnapperLinearLayoutManager which wraps this behavior in a layout manager along with other handy features.

for more info and examples check here

kalin
  • 3,546
  • 2
  • 25
  • 31