Whenever I type into my search view the close button (X) appears to be disabled for some reason rather than appearing in the colour white. How can this error be resolved so that it appears white?
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_search_list, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
searchView.setQueryHint(getResources().getString(R.string.station_search_hint));
}
menu_search_list.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search_light"
android:title="@string/action_search"
android:orderInCategory="100"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
Clean solution hiding the close icon when is empty.
Use "collapseActionView|always" in app:showAsAction attribute.
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_search"
android:title="@string/menu_action_search"
app:showAsAction="collapseActionView|always"
app:actionViewClass="android.support.v7.widget.SearchView"/>
Your code seems fine. Try out the following code:
final MenuItem search = menu.findItem(R.id.action_search);
if (search != null) {
SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
search.expandActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
// Your Logic
return false;
}
});
MenuItemCompat.setOnActionExpandListener(search, new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return false;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
finish();
return true;
}
});
One more tweak:
Try the same above code in onPrepareOptionsMenu
with following extra lines at the top
menu.clear();
getMenuInflater().inflate(R.menu.menu_search_list, menu);
...
// Above code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With