RecyclerView scrollToPosition not trigger scrollListener

前端 未结 8 2150
予麋鹿
予麋鹿 2021-02-01 03:35

I\'m using RecyclerView, with ScrollListener:

mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener()
{
        @Override
        public void onScr         


        
8条回答
  •  -上瘾入骨i
    2021-02-01 04:03

    I could not use the smoothScrollToPosition (we had some problems with it in the past) and depending on the position of the first item seemed unreliable, so I ended up using yigit's answer (it has been released already), unfortunately it didn't always work (I am not sure why).

    So I ended up using a scroll listener I've added previously to the RecyclerView, sadly I cannot find the origin of this solution.
    I don't think you should use this listener if you need a constant one, luckily I need to listen only at specific times.

    Override the RecyclerView:

    public class MyRecyclerView extends RecyclerView {
    
        public interface OnScrollStoppedListener{
            void onScrollStopped();
        }
    
        private static final int NEW_CHECK_INTERVAL = 100;
        private OnScrollStoppedListener mOnScrollStoppedListener;
        private Runnable mScrollerTask;
        private int mInitialPosition;
    
        public MyRecyclerView(Context context) {
            super(context);
            init();
        }
    
        public MyRecyclerView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public MyRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }
    
        private void init() {
            mScrollerTask = new Runnable() {
                public void run() {
                    int newPosition = getScrollY();
                    if(mInitialPosition - newPosition == 0) {//has stopped
                        if(mOnScrollStoppedListener !=null) {
                            mOnScrollStoppedListener.onScrollStopped();
                        }
                    } else {
                        startScrollerTask();
                    }
                }
            };
        }
    
        public void setOnScrollStoppedListener(MyRecyclerView.OnScrollStoppedListener listener){
            mOnScrollStoppedListener = listener;
        }
    
        public void startScrollerTask() {
            mInitialPosition = getScrollY();
            postDelayed(mScrollerTask, NEW_CHECK_INTERVAL);
        }
    
    }  
    

    Usage:

    myRecyclerView.setOnScrollStoppedListener(new MyRecyclerView.OnScrollStoppedListener() {
        @Override
        public void onScrollStopped() {
            // Do your thing
        }
    });
    
    myRecyclerView.startScrollerTask();
    

提交回复
热议问题