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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With