SearchView getActionView returning null

Axxiss picture Axxiss · Aug 23, 2013 · Viewed 29.3k times · Source

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);
}

Answer

maxandron picture maxandron · Sep 10, 2015

I had the same problem because in my menu I used: android:actionViewClass="android.widget.SearchView" as per the google documentation.

Well it turns out that if I'm using AppCompatActivity I should use app:actionViewClass="android.widget.SearchView" instead.

Hope this helps someone.