Search code examples
androidandroid-actionbarsearchview

How to match behavior in SearchView onBackPressed() with home up navigation


When using the SearchView in the action bar, and it has the focus then there is a slight difference between:

  1. Pressing the back button
  2. Using the home up navigation (icon in the top left)

With 1. the focus is cleared, the input field disappears, but the icon sticks to left (instead where it was, the right).

With 2. not only the focus is cleared, but the icon goes back to the right side and the activity title is displayed again.

How can I achieve, that with the back button press the same behavior as with 2. is achieved?


Solution

  • Override "onBackPressed" method of Activity to get your desired result:

    @Override
    public void onBackPressed() {
        onNavigateUp();
    }
    

    Or if your application support lower versions than API Level 16, use:

    @Override
    public void onBackPressed() {
        onSupportNavigateUp();
    }