问题描述:

I have an app which uses a CoordinatorLayout and a NavigationDrawer. However, whenever I go to open the NavigationView (by swiping from edge of device screen), my app crashes with the following error:

java.lang.NullPointerException: Attempt to invoke virtual method 'float android.view.MotionEvent.getX()' on a null object reference

at android.view.View.onTouchEvent(View.java:9409)

at android.support.design.widget.CoordinatorLayout.onTouchEvent(CoordinatorLayout.java:449)

at android.view.View.dispatchTouchEvent(View.java:8471)

at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2373)

at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2092)

at android.support.v4.widget.DrawerLayout.cancelChildViewTouch(DrawerLayout.java:1668)

at android.support.v4.widget.DrawerLayout$ViewDragCallback.peekDrawer(DrawerLayout.java:1916)

at android.support.v4.widget.DrawerLayout$ViewDragCallback.access$000(DrawerLayout.java:1801)

at android.support.v4.widget.DrawerLayout$ViewDragCallback$1.run(DrawerLayout.java:1807)

at android.os.Handler.handleCallback(Handler.java:739)

at android.os.Handler.dispatchMessage(Handler.java:95)

at android.os.Looper.loop(Looper.java:135)

at android.app.ActivityThread.main(ActivityThread.java:5254)

at java.lang.reflect.Method.invoke(Native Method)

at java.lang.reflect.Method.invoke(Method.java:372)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

I tried overriding the touch event methods:

@Override

public boolean dispatchTouchEvent(MotionEvent ev) {

try {

return super.dispatchTouchEvent(ev);

} catch (Exception e) {

return false;

}

}

@Override

public boolean onTouchEvent(MotionEvent ev) {

try {

return super.onTouchEvent(ev);

} catch (Exception e) {

return false;

}

}

but that didn't help. Is there anyway that I can fix this error?

All advice is appreciated

网友答案:

Alright so I was able to fix things by:

Overriding the methods shown in my question:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    try {
        return super.dispatchTouchEvent(ev);
    } catch (Exception e) {
        return false;
    }
}

@Override
public boolean onTouchEvent(MotionEvent ev) {
    try {
        return super.onTouchEvent(ev);
    } catch (Exception e) {
        return false;
    }
}

and setting an onTouchListener for my CoordinatorLayout:

coordinatorLayout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true; //make sure to return true
        }
    });
相关阅读:
Top