Need code to close the searchView when BACK is pressed. So far only have code that closes the keyboard when BACK is pressed.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (item.getItemId() == android.R.id.home) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View view = this.getCurrentFocus();
if (view != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
return super.onOptionsItemSelected(item);
}
I tried the following line but this line closes the entire app for some reason when "back" clicked on...
onBackPressed();
The following line is deprecated...
MenuItemCompat.collapseActionView(menuItem);
I've seen some answers on stackOverflow but most of them have to do with onBackPressed()
or adding searchView.collapseActionView()
.
But I can't add searchView in onOptionsItemSelected(MenuItem item)
unless I redeclare it with SearchView searchView = (SearchView) item.getActionView();
and then add searchView.collapseActionView()
but then the app crashes when BACK pressed.
I got the keyboard to close but how do I close the searchView in onOptionsItemSelected(MenuItem item)
?
EDIT:
When I use onBackPressed()
or super.onBackPressed()
or this.onBackPressed()
, the first time I click on "back" button, searchView and keyboard close, but when I click on search Icon again to open searchView and keyboard pops up, if I click on "back" again, the entire app closes, not crashes, just closes and takes me to Android Phone home screen. Why is this happening?