How to scroll recyclerView programmatically?
Use this..
int top = 0;
recyclerView.smoothScrollToPosition(top); // for top
int bottom = recyclerView.getAdapter().getItemCount()-1;
recyclerView.smoothScrollToPosition(bottom);
if you need scroll item of recyclerview to CENTER of screen when for ex. expand your item - use this way:
in app/build.gradle - insert:
implementation 'com.andkulikov:transitionseverywhere:1.7.4'
when hadle click in onBindViewHolder of adapter - insert:
AutoTransition transitionPort = new AutoTransition();
transitionPort.setDuration(100);
transitionPort.addListener(new Transition.TransitionListener() {
@Override
public void onTransitionStart(@NonNull Transition transition) {
recyclerView.setEnabled(false);
recyclerView.setClickable(false);
}
@Override
public void onTransitionEnd(@NonNull Transition transition) {
recyclerView.post(() -> recyclerView.smoothScrollToPosition(position));
recyclerView.setEnabled(true);
recyclerView.setClickable(true);
}
@Override
public void onTransitionCancel(@NonNull Transition transition) {
recyclerView.setEnabled(true);
recyclerView.setClickable(true);
}
@Override
public void onTransitionPause(@NonNull Transition transition) {
}
@Override
public void onTransitionResume(@NonNull Transition transition) {
}
});
TransitionManager.beginDelayedTransition(recyclerView, transitionPort);
You can use scrollToPosition()
recyclerView.post(new Runnable() {
@Override
public void run() {
recyclerView.scrollToPosition(adapter.getItemCount() - 1);
// Here adapter.getItemCount()== child count
}
});
or smoothScrollToPosition()
recyclerView.post(new Runnable() {
@Override
public void run() {
recyclerView.smoothScrollToPosition(adapter.getItemCount()- 1);
}
});
To move up again, you need to call the above method with index 0. But first, you need to make sure that the RecyclerView
is scrolled to last.
So, put a ScrollListener
on RecyclerView
to make sure the last item is visible.