Search code examples
androidkeydetectback

How to detect Back Key in my CustomView


I want to detect Back Key event in my CustomView (e.g., EditText). In many case, it has been achieved by overriding the onKeyDown() or dispatchKeyEvent(), under the condition that my CustomView obtains focus.

CustomView.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if( keyCode == KeyEvent.KEYCODE_BACK) {
        ..... 
        return true;
    }else{
        return super.onKeyDown(keyCode, event);
    }
}

However, if an Activity including the CustomView is also overriding the onKeyDown() or dispatchKeyEvent(), it couldn't work much. That is, the Activity has obtained the Back-KeyEvent before the CustomView has.

I preferentially want to catch the Back-KeyEvent before Activity does.

please tell me some ideas about this problem. Thank you.


Solution

  • You need to implement this to capture the BACK button before it is dispatched to the IME:

    http://developer.android.com/reference/android/view/View.html#onKeyPreIme(int,android.view.KeyEvent)