NestedScrollView與Viewpager滑動衝突

原文鏈接:https://blog.csdn.net/xiaoshuxgh/article/details/84935714

轉載出處
最近實現需求Viewpager實現加載視頻和圖片實現輪播,所實現的界面需要嵌套NestedScrollView,所出現的問題就是:Viewpager可以實現自動輪播,但是不能實現手動輪播,這是我很鬱悶,一想肯定是滑動衝突了,網上也找了很多的解決辦法。後邊得到NestedScrollView依然消費事件,所以我們還需要對NestedScrollView事件進行處理,判斷如果是左右滑動的時候,我們不讓NestedScrollView處理,而是交給子View處理,即ViewPager

下面直接上代碼:

public class JudgeNestedScrollView extends NestedScrollView {
    private boolean isNeedScroll = true;
    private float xDistance, yDistance, xLast, yLast;

    public JudgeNestedScrollView(@NonNull Context context) {
        super(context);
    }
    
    public JudgeNestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    
    public JudgeNestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDistance = yDistance = 0f;
                xLast = ev.getX();
                yLast = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                xDistance += Math.abs(curX - xLast);
                yDistance += Math.abs(curY - yLast);
                xLast = curX;
                yLast = curY;
                if (xDistance > yDistance) {
                    return false;
                }
                return isNeedScroll;

        }
        return super.onInterceptTouchEvent(ev);
    }

    /*
    改方法用來處理NestedScrollView是否攔截滑動事件
     */
    public void setNeedScroll(boolean isNeedScroll) {
        this.isNeedScroll = isNeedScroll;
    }
}

至此問題完美解決。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章