Reputation: 21893
getActionView() is retuning null. What am i doing wrong?
I am extending Activity and using android:minSdkVersion="11" android:targetSdkVersion="19"
<item
android:id="@+id/search"
android:actionViewClass="android.widget.SearchView"
android:icon="@drawable/ic_action_search"
android:showAsAction="collapseActionView|ifRoom"
app:showAsAction="always"
android:title="@string/search"/>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
searchItem = menu.findItem(R.id.search);
mSearchView = (SearchView) searchItem.getActionView();
mSearchView.setQueryHint("Search");
return true;
}
manifest
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
</activity>
Upvotes: 1
Views: 758
Reputation: 6797
I saw that you have app:showAsAction="always"
the app
namespace means that you are using Appcompat v7 library ...
Appcompat library has it owns method for menu items as static method in MenuCompat
/MenuItemCompat
classes (and you should use 'em like instead menu.methodXXX()
use MenuCompat.methodXXX(menu)
)
Now, to define a actionViewClass
(and others attributes added in api newer then 11) in menu you should use the app
namespace for this instead android
namespace
so android:actionViewClass
should become app:actionViewClass
in the code you should use MenuItemCompat.getActionView(searchItem)
instead searchItem.getActionView()
remeber to add namespace app
in root element of menu xml file like xmlns:app ="http://schemas.android.com/apk/res-auto"
also small hint (as you are using 11 as min sdk your code should works fine but ...) replace android.widget.SearchView
to android.support.v7.widget.SearchView
as it(standard SearchView) not works in the same way on different API versions from 11 to newest one(also you will get method not found if you use methods added in API > 11 to SearchView on devce with API 11)
Upvotes: 2