Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView with SnapHelper, item is not snapped after scrollToPosition

I have a RecyclerView in my activity and a LinearSnapHelper attached to it:

TimePickerAdapter timePickerAdapter = new TimePickerAdapter(hours);
recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);

final SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);

The problem is that when I want to initially scroll to a specific item, the snap helper is not being triggered to attach the item (see the image):

recyclerView.getLayoutManager().scrollToPosition(timePickerAdapter.getCurrentPosition());

When I scroll with my hand it starts to work as expected. Any solutions to this?

enter image description here

like image 345
dragoon Avatar asked Dec 22 '16 09:12

dragoon


1 Answers

SnapHelper rely on RecyclerView.OnFlingListener#onFling() or RecyclerView.OnScrollListener#onScrollStateChanged(recyclerView, RecyclerView.SCROLL_STATE_IDLE) to trigger snap action.

But scrollToPosition() will not tigger above callback. You can invoke smoothScrollBy(1, 0) after scrollToPosition() to trigger SnapHelper to scroll.

like image 111
Samuel Avatar answered Sep 28 '22 07:09

Samuel