0

I have an activity with search bar. On start, keyboard shows up.

If I hit back button, it dismisses the keyboard. I need to hit back button 3 times to dismiss activity. The first hit dismisses keyboard, second hit loses focus from search bar.

How to dismiss activity using back button?

James Z
  • 12,209
  • 10
  • 24
  • 44
GJain
  • 5,025
  • 6
  • 48
  • 82
  • Possible duplicate of [Android key event for back key when soft keyboard is shown?](https://stackoverflow.com/questions/19637272/android-key-event-for-back-key-when-soft-keyboard-is-shown) – Elam parithi Feb 01 '19 at 11:41
  • remove super from onBackpressed and use finish() – karan Feb 01 '19 at 11:46

1 Answers1

0

You can catch back event and add your own destination activity as follows

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
        // finish current activity  ( finish(); )
        // add your new intent here
        // Example:
        // startActivity(new Intent(<your_context>, <destination_activity>));
    }
    return super.onKeyDown(keyCode, event);
}
Farid Haq
  • 3,728
  • 1
  • 21
  • 15
  • This code only gets executed on 3rd hit of device back key. The first hit dismissed keyboard, second hit loses focus from search bar. – GJain Feb 01 '19 at 00:31
  • 1
    If you want to disable default behavior of `onKeyDown`, return `true` instead of `super` – Bach Vu Feb 01 '19 at 01:07