This was working a few days ago, but suddenly it stopped. I only want to use the action bar search widget when certain fragment is visible.
Now I'm unable to get the SearchView
, now getActionView
always returns null.
searchable.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>
Manifest.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>
menu.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>
The fragment
...
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);
}
Today I had the same problem and I think I solved it. It turns out I did couple of things that were not exactly as per the
ActionBarCompat
contract:ActionBarCompat
should extendActionBarActivity
instead ofFragmentActivity
directlyActionBarCompat
should declare its theme as inheriting from theActionBarCompat
themes.Both of those I found watching the explanation video from Google.
Now my
searchView
is notnull
anymore.