我正在尝试将 Search-ActionView 添加到我的应用程序中(如此处所述http://developer.android.com/guide/topics/search/search-dialog.html#UsingSearchWidget)。不幸的是,我不断收到 NullPointerException,我很难检测出实际出了什么问题。
我创建了一个可搜索的配置和一个可搜索的活动,如 android 页面所示。我的菜单 .xml 文件如下所示:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
...
<item
android:id="@+id/menu_item_search"
android:actionViewClass="android.widget.SearchView"
android:icon="@drawable/icon_search"
android:showAsAction="always"
android:title="@string/action_bar_button_search">
</item>
</menu>
这是抛出异常的方法:
public boolean onCreateOptionsMenu( Menu menu )
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate( R.menu.action_bar, menu );
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_item_search).getActionView();
// NullPointerException thrown here; searchView is null.
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
return super.onCreateOptionsMenu( menu );
}
完整的堆栈跟踪:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.activities.Test.onCreateOptionsMenu(Test.java:41)
at android.app.Activity.onCreatePanelMenu(Activity.java:2444)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:408)
at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:759)
at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:2997)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4507)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)