RecyclerView scrollToPosition not trigger scrollListener

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

I\'m using RecyclerView, with ScrollListener:

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


        
8条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-01 04:07

    It's a bit rudimentary, but you could try this Subclass of RecyclerView:

    public class PatchedRecyclerView extends RecyclerView {
    
        private OnScrollListener listener;
    
        public PatchedRecyclerView(Context context) {
            super(context);
        }
    
        public PatchedRecyclerView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public PatchedRecyclerView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        public void setOnScrollListener(OnScrollListener listener) {
            super.setOnScrollListener(listener);
            this.listener = listener;
        }
    
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
    
            int preFirstChildPosition = getChildCount() != 0 ? getChildViewHolder(getChildAt(0)).getPosition() : -1;
            int preLastChildPosition = getChildCount() != 0 ? getChildViewHolder(getChildAt(getChildCount() - 1)).getPosition() : -1;
            super.onLayout(changed, l, t, r, b);
            int postFirstChildPosition = getChildCount() != 0 ? getChildViewHolder(getChildAt(0)).getPosition() : -1;
            int postLastChildPosition = getChildCount() != 0 ? getChildViewHolder(getChildAt(getChildCount() - 1)).getPosition() : -1;
    
            // TODO: Insert proper DX and DY values
            if (preFirstChildPosition != postFirstChildPosition || preLastChildPosition != postLastChildPosition)
                listener.onScrolled(this, 0, 0);
        }
    }
    

提交回复
热议问题