您好,我在应用程序中实现搜索小部件时遇到了问题。似乎无法找到菜单项的“actionview”,但是它能够很好地找到该项。
我已经寻找答案,但没有看到明确的解决方案。
以下是我在XML中声明的菜单:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/group_search_box"
android:title="@string/search_label"
android:icon="@drawable/ic_action_action_search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
以下是它的实现方式。
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
MenuItem searchMenuItem = menu.findItem(R.id.group_search_box);
SearchView searchView = (SearchView) searchMenuItem.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
这里是我正在添加的库,也许我添加了一个不正确的库?
compile 'com.android.support:support-v4:+'
compile 'com.android.support:appcompat-v7:+'
最后,这是崩溃日志。
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)' on a null object reference
at com.example.myapp.fragments.GroupFragment.onCreateOptionsMenu(GroupFragment.java:88)
at android.app.Fragment.performCreateOptionsMenu(Fragment.java:1780)
at android.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1927)
at android.app.Activity.onCreatePanelMenu(Activity.java:2539)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:224)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:436)
at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:800)
at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:221)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:543)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
我完全按照文档的要求操作,但仍然无法解决问题。