我在操作栏中将搜索视图作为选项菜单
在onCreateOptionsMenu
方法中,我得到了如下搜索视图
inflater.inflate(R.menu.main, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.serach).getActionView();
当我尝试设置setOnQueryTextListener
时,它会给我空指针异常。
我的代码如下
mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String arg0) {
return true;
}
@Override
public boolean onQueryTextChange(String arg0) {
return false;
}
});
当我删除监听器时它工作正常。 有人能说出我做错了什么。
logcat log
02-11 20:04:15.574: E/AndroidRuntime(27028): FATAL EXCEPTION: main
02-11 20:04:15.574: E/AndroidRuntime(27028): java.lang.NullPointerException
02-11 20:04:15.574: E/AndroidRuntime(27028): at com.example.test.PM_Fragment.onCreateOptionsMenu(PM_Fragment.java:61)
02-11 20:04:15.574: E/AndroidRuntime(27028): at android.app.Fragment.performCreateOptionsMenu(Fragment.java:1865)
02-11 20:04:15.574: E/AndroidRuntime(27028): at android.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1919)
02-11 20:04:15.574: E/AndroidRuntime(27028): at android.app.Activity.onCreatePanelMenu(Activity.java:2552)
02-11 20:04:15.574: E/AndroidRuntime(27028): at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:479)
02-11 20:04:15.574: E/AndroidRuntime(27028): at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:845)
02-11 20:04:15.574: E/AndroidRuntime(27028): at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:273)
02-11 20:04:15.574: E/AndroidRuntime(27028): at android.os.Handler.handleCallback(Handler.java:725)
02-11 20:04:15.574: E/AndroidRuntime(27028): at android.os.Handler.dispatchMessage(Handler.java:92)
02-11 20:04:15.574: E/AndroidRuntime(27028): at android.os.Looper.loop(Looper.java:158)
02-11 20:04:15.574: E/AndroidRuntime(27028): at android.app.ActivityThread.main(ActivityThread.java:5751)
02-11 20:04:15.574: E/AndroidRuntime(27028): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 20:04:15.574: E/AndroidRuntime(27028): at java.lang.reflect.Method.invoke(Method.java:511)
02-11 20:04:15.574: E/AndroidRuntime(27028): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
02-11 20:04:15.574: E/AndroidRuntime(27028): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
02-11 20:04:15.574: E/AndroidRuntime(27028): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:2)
我怎么会这么愚蠢。
我在searchView
获得了搜索视图,我正在设置mSearchView
的监听器。这完全是我的错误