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):
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?