1

Need code to close the searchView when BACK is pressed. So far only have code that closes the keyboard when BACK is pressed.

enter image description here

@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?

iBEK
  • 622
  • 2
  • 8
  • 27

1 Answers1

1

Update

 @Override
    public void onBackPressed() {
        if (!yourSearhView.isIconified()) {
            yourSearhView.onActionViewCollapsed();
        } else {
            super.onBackPressed();
        }
    }

This won't work if the you have set app:showAsAction="always"

diegoveloper
  • 93,875
  • 20
  • 236
  • 194
  • This code don't work for me, I've seen it on stackOverflow. – iBEK Nov 14 '17 at 20:31
  • You know of code I can place inside onOptionsItemSelected that won't require me to use "searchView". Like the keyboard hide code, where I didn't have to input "searchView". – iBEK Nov 14 '17 at 20:32