The problem with the code is SearchView
is not a MenuItem
so cannot be obtained by menu.findItem
. You have to get the menu item for search first and then get your SearchView
.
Replace the failing line with -
mSearchMenuItem = menu.findItem(R.id.action_search);
mSearchView = (EnglishVerbSearchView) MenuItemCompat.
getActionView(mSearchMenuItem);
WHERE,
R.id.action_search
is the id of your search item in the menu.
Also since you are using the compat library so your menu xml file should contain the yourapp
namespace.
For example --
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item android:id="@+id/action_search"
android:title="@string/action_search"
android:icon="@drawable/action_search"
yourapp:showAsAction="always|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
NOTE:
Application can be anything, in the above example as it is yourapp
. It has to point to http://schemas.android.com/apk/res-auto
schema though.
The typical example with account to your problem is shown at:
Android-nullpointerexception-on-searchview-in-action-bar.
The code is included above for clarity of the problem.
UPDATE:
To clear your mistakes in the xml look at the following code of your xml -
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<!-- xmlns:yourapp="http://schemas.android.com/apk/res-auto" -->
<!-- Search / will display always -->
<item android:id="@+id/action_search"
android:title="@string/action_search"
android:icon="@drawable/ic_action_search"
android:showAsAction="ifRoom|collapseActionView"
android:actionViewClass="android.widget.searchview"/>
Just replace the above code with the following ---
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto">
<!-- Search / will display always -->
<item android:id="@+id/action_search"
android:title="@string/action_search"
android:icon="@drawable/ic_action_search"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="android.widget.searchview"/>
Please note the changes in line 2, 7 and 8.
SOURCE: Action View Bar.
Hope this will help you!
android.support.v7.widget.SearchView
in your xml andMenuItemCompat
in your code so you're clearly using the support library.