在父viewPager中禁用子viewPager滑动

时间:2015-02-13 05:18:07

标签: android android-viewpager ontouchevent

我想禁用子viewpager的刷卡。

我目前使用此自定义子viewpager

public class CustomViewPager extends ViewPager {

public CustomViewPager(Context context) {
    super(context);
}

public CustomViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return true;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return true;
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {

    return true;
}
}

禁用子viewpager的滑动,但在该部分禁用父viewpager滑动。

2 个答案:

答案 0 :(得分:5)

要在不影响父事件的情况下禁用ViewPager滚动,请覆盖canScrollHorizo​​ntally()方法:

@Override
    public boolean canScrollHorizontally(int direction) {
        //Disable horizontal scrolling
        if (enabled) {
            return super.canScrollHorizontally(direction);
        } else {
            return false;
        }
    }

答案 1 :(得分:1)

您应该从子ViewPager中的onInterceptTouchEventonTouchEvent返回false。从onTouchEvent返回True将告诉父级视图已成功处理事件,这不是您想要的。

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;
}