java.lang.IllegalArgumentExcepti

2018-04-12  本文已影响0人  CZKGO

问题:

java.lang.IllegalArgumentException: pointerIndex out of range
  at android.view.MotionEvent.nativeGetAxisValue (MotionEvent.java)
  at android.view.MotionEvent.getX (MotionEvent.java:2139)
  at android.support.v4.view.ViewPager.onInterceptTouchEvent (ViewPager.java)
  at my.test.app.view.CustomViewPager.onInterceptTouchEvent (CustomViewPager.java)
  at android.view.ViewGroup.dispatchTouchEvent (ViewGroup.java:2212)
  at android.view.ViewGroup.dispatchTransformedTouchEvent (ViewGroup.java:2669)
  at android.view.ViewGroup.dispatchTouchEvent (ViewGroup.java:2358)
  at android.view.ViewGroup.dispatchTransformedTouchEvent (ViewGroup.java:2669)
  at android.view.ViewGroup.dispatchTouchEvent (ViewGroup.java:2358)
  at android.view.ViewGroup.dispatchTransformedTouchEvent (ViewGroup.java:2669)
  at android.view.ViewGroup.dispatchTouchEvent (ViewGroup.java:2358)
  at android.view.View.dispatchPointerEvent (View.java:10164)
  at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent (ViewRootImpl.java:4490)
  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess (ViewRootImpl.java:4358)
  at android.view.ViewRootImpl$InputStage.deliver (ViewRootImpl.java:3900)
  at android.view.ViewRootImpl$InputStage.onDeliverToNext (ViewRootImpl.java:3953)
  at android.view.ViewRootImpl$InputStage.forward (ViewRootImpl.java:3919)
  at android.view.ViewRootImpl$AsyncInputStage.forward (ViewRootImpl.java:4046)
  at android.view.ViewRootImpl$InputStage.apply (ViewRootImpl.java:3927)
  at android.view.ViewRootImpl$AsyncInputStage.apply (ViewRootImpl.java:4103)
  at android.view.ViewRootImpl$InputStage.deliver (ViewRootImpl.java:3900)
  at android.view.ViewRootImpl$InputStage.onDeliverToNext (ViewRootImpl.java:3953)
  at android.view.ViewRootImpl$InputStage.forward (ViewRootImpl.java:3919)
  at android.view.ViewRootImpl$InputStage.apply (ViewRootImpl.java:3927)
  at android.view.ViewRootImpl$InputStage.deliver (ViewRootImpl.java:3900)
  at android.view.ViewRootImpl.deliverInputEvent (ViewRootImpl.java:6266)
  at android.view.ViewRootImpl.doProcessInputEvents (ViewRootImpl.java:6240)
  at android.view.ViewRootImpl.enqueueInputEvent (ViewRootImpl.java:6201)
  at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent (ViewRootImpl.java:6369)
  at android.view.InputEventReceiver.dispatchInputEvent (InputEventReceiver.java:185)
  at android.os.MessageQueue.nativePollOnce (MessageQueue.java)
  at android.os.MessageQueue.next (MessageQueue.java:323)
  at android.os.Looper.loop (Looper.java:136)
  at android.app.ActivityThread.main (ActivityThread.java:6195)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:874)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:764)

原因

  在ViewPager上做View滑动是,需要禁掉ViewPager的滑动,这时创建了继承自ViewPager的CustomViewPager来实现该功能,并重写了onInterceptTouchEvent方法,并使用canScroll来决定是否允许ViewPager滑动。代码如下:

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if(canScroll){
                return super.onInterceptTouchEvent(ev)
        }else{
            return false;
        }
    }

  这段代码在运行时抛出了上文异常(非必现)。这个异常是怎么产生的呢?根据堆栈信息,我追踪到MotionEvent类的MotionEvent方法,该方法如下:

  @FastNative
    private static native float nativeGetAxisValue(long nativePtr,
            int axis, int pointerIndex, int historyPos);

  可以看到该方法被@FastNative标记,这表示可实现对 Java 原生接口 (JNI) 更快速的原生调用。也就是说该方法在jni包下实现,然后找到android_view_MotionEvent.cpp文件,得到如下函数:

static jfloat android_view_MotionEvent_nativeGetAxisValue(JNIEnv* env, jclass clazz,
        jlong nativePtr, jint axis, jint pointerIndex, jint historyPos) {
    MotionEvent* event = reinterpret_cast<MotionEvent*>(nativePtr);
    size_t pointerCount = event->getPointerCount();
    if (!validatePointerIndex(env, pointerIndex, pointerCount)) {
        return 0;
    }
    if (historyPos == HISTORY_CURRENT) {
        return event->getAxisValue(axis, pointerIndex);
    } else {
        size_t historySize = event->getHistorySize();
        if (!validateHistoryPos(env, historyPos, historySize)) {
            return 0;
        }
        return event->getHistoricalAxisValue(axis, pointerIndex, historyPos);
    }
}

  再从该函数找到validatePointerIndex函数,也就是该异常出处

static bool validatePointerIndex(JNIEnv* env, jint pointerIndex, size_t pointerCount) {
    if (pointerIndex < 0 || size_t(pointerIndex) >= pointerCount) {
        jniThrowException(env, "java/lang/IllegalArgumentException",
                "pointerIndex out of range");
        return false;
    }
    return true;
}

  由代码可知,当pointerIndex 小于0或者大于pointerCount时抛出该异常。

解決方案

方案一:捕获该异常
  从上文可知当pointerIndex 小于0或者大于pointerCount时抛出该异常。我并没有在代码中改变该值,所以直接捕获即可。

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if(canScroll){
            try {
                return super.onInterceptTouchEvent(ev);
            } catch (Exception e) {
                return false;
            }
        }else{
            return false;
        }
    }

方案二:提前做判断
  从上文可知当pointerIndex 小于0或者大于pointerCount时抛出该异常。那么我们可以前进行该判断来避免异常。pointerCount可以通过MotionEvent类的getPointerCount()方法获得,pointerIndex 根据堆栈信息可知得自MotionEvent.getX方法的。而ViewPager.onInterceptTouchEvent 方法中有两处MotionEvent.getX方法调用,分别如下:

//...代码省略
        switch (action) {
            case MotionEvent.ACTION_MOVE: {
                //...代码省略
                final int activePointerId = mActivePointerId;
                if (activePointerId == INVALID_POINTER) {
                    // If we don't have a valid id, the touch down wasn't on content.
                    break;
                }
                final int pointerIndex = ev.findPointerIndex(activePointerId);
                final float x = ev.getX(pointerIndex);
                //...代码省略
            }
            case MotionEvent.ACTION_DOWN: {
                /*
                * Remember location of down touch.
                * ACTION_DOWN always refers to pointer index 0.
                */
                 mLastMotionX = mInitialMotionX = ev.getX();
                //...代码省略
            }
//...代码省略

  从代码中可以看出第一处MotionEvent.getX方法调用,其pointerIndex 来源如下:

final int activePointerId = mActivePointerId;
if (activePointerId == INVALID_POINTER) {
     // If we don't have a valid id, the touch down wasn't on content.
     break;
}
final int pointerIndex = ev.findPointerIndex(activePointerId)

  第二处调用的是无参数的MotionEvent.getX方法,该方法传入的参数为0,因为getPointerCount()的注释中有提到该方法返回值 >= 1,所以不会抛出该异常。无参数的MotionEvent.getX方法代码如下:

   public final float getX() {
        return nativeGetAxisValue(mNativePtr, AXIS_X, 0, HISTORY_CURRENT);
    }

  综上所述,我们只需要在MotionEvent.ACTION_MOVE时参照上文获取pointerIndex 和pointerCount进行一次判断即可,这里需要注意的是mActivePointerId是私有属性,需要反射获取。INVALID_POINTER是常量,直接用-1替代即可。解决代码如下:

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_MOVE:
                try {
                    Field field = this.getClass().getSuperclass().getDeclaredField("mActivePointerId");
                    field.setAccessible(true);
                    final int mActivePointerId = (int) field.get(this);
                    if (mActivePointerId != -1) {
                        final int pointerIndex = ev.findPointerIndex(mActivePointerId);
                        if(pointerIndex < 0 || pointerIndex >= ev.getPointerCount()){
                            return false;
                        }

                    }
                    break;
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
        }
        if (isCanScroll) {
            return super.onInterceptTouchEvent(ev);
        } else {
            return false;
        }

    }
上一篇下一篇

猜你喜欢

热点阅读