Reputation: 53
I'm trying to make a dynamic action bar in android, right now I'm trying to make a search in the action bar like this.
http://developer.android.com/images/ui/[email protected]
However when I click the the search button in the action bar nothing happens.
Here is the menu XML file:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto" >
<item android:id="@+id/action_search"
android:title=""
android:icon="@drawable/abc_ic_search"
android:showAsAction="ifRoom|collapseActionView"
android:actionViewClass="android.support.v7.widget.SearchView"/>
<item android:id="@+id/action_menu"
android:title=""
android:icon="@drawable/abc_ic_menu"
android:showAsAction="always"
android:actionViewClass="android.support.v7.widget.ShareActionProvider"/>
Here is the OnCreateOptionsMenu in the Activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
return true;
}
I know the icon I have in the action bar is working because I have this code working without problems
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(getBaseContext(), "Search icon is working", Toast.LENGTH_LONG).show();
return true;
case R.id.action_menu:
Toast.makeText(getBaseContext(), "Menu icon is working", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I think it has something to do with this:
android:actionViewClass="android.support.v7.widget.SearchView"/>
Because even when I delete the android.support.v7 jar on the project (I just deleted it to test, I have it back again) I can execute the project without any errors. So maybe the XML file doesn't recognise the android.support.v7 path?
P.S: the action_menu icon doesn't work either.
Upvotes: 1
Views: 1601
Reputation: 2506
Additionally android.support.v7.widget.SearchView
throws NullPointerException
at onCreateOptionsMenu()
with default configuration.
Solved by changing it to android.widget.SearchView
The answer by @CommonsWare is valid also. It is more likely to be the correct answer.
Upvotes: 0
Reputation: 1006654
I know the icon I have in the action bar is working because I have this code working without problems
That is consuming the event, preventing the SearchView
from working. Please delete both case
sections of this method, as they are incorrect for both of your menu items.
(and, please use this
, not getBaseContext()
, unless you know what getBaseContext()
does)
Here is a sample app showing the use of SearchView
.
Upvotes: 2