解决swipeRefreshLayout与RecyclerView的滑动冲突

网上给出的最多的滑动冲突解决办法思路:首先给RecyclerView添加滑动监听事件,其次获取recyclerView的第一个子布局的位置,如果你是上滑的话,recyclerView.getChildAt(0).getTop()获取的值肯定是个负数,当第一个item项出现,并且在顶部时swipeRefreshLayout才能启用,这样解决滑动冲突,但是这个方法在部分手机上不兼容。
网上的源码大概是这样的:

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int topRowVerticalPosition =
                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                swipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0);

            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });

其实这样判断是有缺陷的,改成如下

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int topRowVerticalPosition =
                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                swipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0 && recyclerView != null && !recyclerView.canScrollVertically(-1));

            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });

recyclerView.canScrollVertically(-1)返回false代表不能下拉了,就是到了顶部,两者需要结合起来判断才能真正解决滑动冲突

你可能感兴趣的:(RecyclerView)