RecyclerView and SwipeRefreshLayout

后端 未结 12 1895
再見小時候
再見小時候 2020-12-22 15:46

I\'m using the new RecyclerView-Layout in a SwipeRefreshLayout and experienced a strange behaviour. When scrolling the list back to the top sometim

12条回答
  •  执念已碎
    2020-12-22 16:06

    The krunal's solution is good, but it works like hotfix and does not cover some specific cases, for example this one:

    Let's say that the RecyclerView contains an EditText at the middle of screen. We start application (topRowVerticalPosition = 0), taps on the EditText. As result, software keyboard shows up, size of the RecyclerView is decreased, it is automatically scrolled by system to keep the EditText visible and topRowVerticalPosition should not be 0, but onScrolled is not called and topRowVerticalPosition is not recalculated.

    Therefore, I suggest this solution:

    public class SupportSwipeRefreshLayout extends SwipeRefreshLayout {
        private RecyclerView mInternalRecyclerView = null;
    
        public SupportSwipeRefreshLayout(Context context) {
            super(context);
        }
    
        public SupportSwipeRefreshLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public void setInternalRecyclerView(RecyclerView internalRecyclerView) {
            mInternalRecyclerView = internalRecyclerView;
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (mInternalRecyclerView.canScrollVertically(-1)) {
                return false;
            }
            return super.onInterceptTouchEvent(ev);
        }
    }
    

    After you specify internal RecyclerView to SupportSwipeRefreshLayout, it will automatically send touch event to SupportSwipeRefreshLayout if RecyclerView cannot be scrolled up and to RecyclerView otherwise.

提交回复
热议问题