我有一个使用CoordinatorLayout和NavigationDrawer的应用。但是,每当我打开NavigationView时(通过从设备屏幕的边缘滑动),我的应用程序崩溃时出现以下错误:
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)
我尝试重写触摸事件方法:
@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;
}
}
但这没有帮助。无论如何我可以解决这个错误吗?
赞赏所有建议
答案 0 :(得分:1)
好吧,所以我能够解决问题:
覆盖我的问题中显示的方法:
@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;
}
}
并为我的CoordinatorLayout设置onTouchListener:
coordinatorLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true; //make sure to return true
}
});