Reputation: 331
I'm using this function to scroll to the selected position inside the horizontal recyclerview. The problem is that if I scroll the recycler and then click an item, it doesn't go to the center of the view. Instead, if I doesn't scroll the recycler, it works. I'm using this method when I click on an item. The position is the adapterPosition.
override fun scrollToSelected(position: Int, isLeftScroll: Boolean) {
if(!isLeftScroll || position == 0) contactRV.layoutManager?.smoothScrollToPosition(contactRV, RecyclerView.State(), position +1)
else contactRV.layoutManager?.smoothScrollToPosition(contactRV, RecyclerView.State(), position-1)
What should I do to solve this problem?
Upvotes: 0
Views: 701
Reputation: 12708
You will Achieve by implementing RecyclerView.SmoothScroller
's method onTargetFound(View, State, Action)
.
/**
* Called when the target position is laid out. This is the last callback SmoothScroller
* will receive and it should update the provided {@link Action} to define the scroll
* details towards the target view.
* @param targetView The view element which render the target position.
* @param state Transient state of RecyclerView
* @param action Action instance that you should update to define final scroll action
* towards the targetView
*/
abstract protected void onTargetFound(View targetView, State state, Action action);
Specifically in LinearLayoutManager
with LinearSmoothScroller
:
public class CenterLayoutManager extends LinearLayoutManager {
public CenterLayoutManager(Context context) {
super(context);
}
public CenterLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public CenterLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
RecyclerView.SmoothScroller smoothScroller = new CenterSmoothScroller(recyclerView.getContext());
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
private static class CenterSmoothScroller extends LinearSmoothScroller {
CenterSmoothScroller(Context context) {
super(context);
}
@Override
public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2);
}
}
}
Upvotes: 2