1

I need to identify the event of back press which hide the softkeyboard
I have tested by override following methods

  1. onKeydown
  2. onBackPressed
  3. onConfigurationChanged
  4. dispatchKeyEvent

But the controller is not reaching there

TofferJ
  • 4,678
  • 1
  • 37
  • 49
Bytecode
  • 6,551
  • 16
  • 54
  • 101

2 Answers2

2

Use dispatchKeyEventPreIme in subclassed EditText view:

@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
    if(KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
       //do what you need here
    }
    return super.dispatchKeyEventPreIme(event);
}
Ludevik
  • 6,954
  • 1
  • 41
  • 59
  • this method is not invoked ,when i cancel the soft keyboard using back button – Bytecode May 20 '11 at 09:46
  • i can't find out this method, i get error when i try to override this function – Bytecode May 23 '11 at 06:29
  • Hm, where do you override it? This method is in [View](http://developer.android.com/reference/android/view/View.html#dispatchKeyEventPreIme%28android.view.KeyEvent%29) since API level 3. Are you extending EditText and implementing it there? – Ludevik May 23 '11 at 07:34
0

An update to @Ludevik's answer

Firstly suggest overriding onKeyDown()

Secondly if the key press has been handled then return true not super.onKeyDown()

Updated code (in Kotlin):

override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
    // if recognise the keyCode then process 
    return if (keyCode == desiredKeyCode) {
        // do what you need to do
        true // key press handled
    } else {
        super.onKeyDown(keyCode, event)
    }
}

As for closing the soft key board - My experience is that can prove problematic (leading to unexpected consequences)

RatherBeSailing
  • 261
  • 1
  • 11