I\'m trying to clear and close SearchView after entering a value. I found a solution but it closes the search and won\'t perform any action if I try to search again.
In menu_main.xml add :
<item android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"
app:showAsAction="collapseActionView|ifRoom"
android:orderInCategory="1"
app:actionViewClass="android.support.v7.widget.SearchView"
android:menuCategory="secondary"
/>
and in onCreateOptionsMenu
final MenuItem miSearch = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) miSearch.getActionView();
searchView.setQueryHint("Searh For");
searchView.setOnQueryTextListener(newSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(context,query, Toast.LENGTH_LONG).show();
// Here Put Your Code.
//searchView.onActionViewCollapsed();
miSearch.collapseActionView();
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
It sounds like what you are looking for is a way to close the search bar programmatically. Unfortunately, there is not a method or an equivalent workaround for this. You may have already seen another post that had some suggestions, but no real way to do this.
Your first edit above that calls setIconified(true)
is the best alternative. The docs suggest calling setIconified(true)
should collapse the search widget, clear it, and remove it from focus if the attribute iconifiedByDefault
is true (which it is by default so I don't see any problem with your activity_main_actions.xml).
Use:
searchMenuItem.collapseActionView();
Instead of:
searchView.onActionViewCollapsed();
If you are using AppCompat library
, then use:
MenuItemCompat.collapseActionView(searchMenuItem);
Solution mentioned here is simple and works perfectly.
Basically, Call setQuery("", false)
and setIconified(true)
on SearchView
.
In my case calling invalidateOptionsMenu();
closes SearchView
Hi i faced a similar scenario and so i think this changed to code should do the trick.
Hope this helps...:)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main_actions, menu);
Menu mMenuItem = menu.findItem(R.id.action_search_loc); // take a reference with menue item
searchView = (SearchView) mMenuItem.getActionView(); //use that to find searchview
searchView.setOnQueryTextListener(searchListener);
return super.onCreateOptionsMenu(menu);
}
SearchView.OnQueryTextListener searchListener = new SearchView.OnQueryTextListener(){
@Override
public boolean onQueryTextChange(String arg0) {
return false;
}
@Override
public boolean onQueryTextSubmit(String query) {
new JsoupGetData("http://api.openweathermap.org/data/2.5/find?q="+ query + "&lang=pl").execute();
try {
mMenuItem.collapseActionView(); //this will collapse your search view
}
catch(Exception ex){
ex.printStackTrace();
System.out.println(ex);
}
return true;
}
};