Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 424
Gottie Avatar asked Jan 31 '12 08:01

Gottie


People also ask

How to detect Back button Press in Android?

In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so. Otherwise, don't exit.

Do all Android devices have Back button?

All Android devices provide a Back button for this type of navigation, so you should not add a Back button to your app's UI. Depending on the user's Android device, this button might be a physical button or a software button.


1 Answers

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)

like image 158
Mohammad Ersan Avatar answered Oct 09 '22 00:10

Mohammad Ersan