1. 程式人生 > >解決SwipeRefreshLayout和ScrollView中巢狀ViewPager卡頓問題

解決SwipeRefreshLayout和ScrollView中巢狀ViewPager卡頓問題

autoCycleViewPager.setOnTouchListener(this);
int downX;
int downY;
int dragthreshold = 30;

@Override
public boolean onTouch(View v, MotionEvent event) {

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            downX = (int) event.getRawX();
            downY = (int) event.getRawY();
            break;
        case MotionEvent.ACTION_MOVE:
            int distanceX = Math.abs((int) event.getRawX() - downX);
            int distanceY = Math.abs((int) event.getRawY() - downY);
            if (distanceX > distanceY) {
                refreshLayout.setEnabled(false);
            }
            if (distanceY > distanceX && distanceY > dragthreshold) {
                autoCycleViewPager.getParent().requestDisallowInterceptTouchEvent(false);
                scrollView.getParent().requestDisallowInterceptTouchEvent(true);
                refreshLayout.setEnabled(true);
            } else if (distanceX > distanceY && distanceX > dragthreshold) {
                refreshLayout.setEnabled(false);
                autoCycleViewPager.getParent().requestDisallowInterceptTouchEvent(true);
                scrollView.getParent().requestDisallowInterceptTouchEvent(false);
            }
            break;
        case MotionEvent.ACTION_UP:
            autoCycleViewPager.getParent().requestDisallowInterceptTouchEvent(false);
            scrollView.getParent().requestDisallowInterceptTouchEvent(false);
            refreshLayout.setEnabled(true);
            break;
        case MotionEvent.ACTION_CANCEL:
            refreshLayout.setEnabled(true);
            break;
    }
    return false;
}

只需要在監聽ViewPager的OnTouch事件上做如上的處理就可以完美解決問題。