几天前这是有效的,但突然停止了。我只想在某些片段可见时使用操作栏搜索小部件。
现在我无法得到SearchView
, nowgetActionView
总是返回 null。
可搜索的.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="@string/search_for_places">
</searchable>
清单.xml
<activity
android:name=".ui.activities.MainActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable"/>
<meta-data
android:name="android.app.default_searchable"
android:value=".ui.activities.MainActivity" />
</activity>
菜单.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search_place"
android:icon="@drawable/ic_2_action_search"
android:orderInCategory="1"
android:title="@string/title_search"
myapp:showAsAction="collapseActionView|ifRoom"
myapp:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
片段
...
setHasOptionsMenu(true);
...
@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search_place);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
SearchManager searchManager = (SearchManager) getBaseActivity().getSystemService(Context.SEARCH_SERVICE);
if (mSearchView != null) {
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
mSearchView.setIconifiedByDefault(true);
mSearchView.setOnQueryTextListener(this);
}
super.onCreateOptionsMenu(menu, inflater);
}