Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check when smoothScrollToPosition has finished

I would like to check when smoothScrollToPosition has finished scrolling back to the first item of recyclerview. I tried doing it like this which only works while smoothScrollToPosition is still scrolling:

recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView,new RecyclerView.State(), 0);
if (!recyclerView.getLayoutManager().isSmoothScrolling()) {
    Log.d(TAG, "Scrolling has ended.");
} 
like image 662
CrimzonWeb Avatar asked Jul 10 '18 09:07

CrimzonWeb


1 Answers

I use onScrollStateChanged(RecyclerView recyclerView, int newState) method for tracking scrolling state. The method to initiate scroll looks like this:

private void scrollToPosition(int position){
    recyclerView.removeOnScrollListener(onScrollListener);
    recyclerView.addOnScrollListener(onScrollListener);
    recyclerView.smoothScrollToPosition(position);
}

And here is the listener:

RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
       @Override
       public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
           switch (newState) {
               case SCROLL_STATE_IDLE:
                   //we reached the target position
                   recyclerView.removeOnScrollListener(this);
                   break;
           }
       }
   };

So, when recyclerView reaches SCROLL_STATE_IDLE, that means it has finished scrolling. Don't forget to remove listener in this state, so it won't trigger on the next scroll.

like image 170
anro Avatar answered Nov 15 '22 20:11

anro