Cómo detectar la tecla Atrás en mi 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.

preguntado el 31 de enero de 12 a las 08:01

3 Respuestas

Debe implementar esto para capturar el botón ATRÁS antes de que se envíe al IME:

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

Respondido el 31 de enero de 12 a las 13:01

Override onKeyDown in your Activity and falso retorno. So that the event gets propagated to other views as well.

If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

Respondido el 31 de enero de 12 a las 12:01

It is not quite true. Method onKeyDown in Activity is called when a key was pressed down and not handled by any of the views inside of the activity.` First is called onKeyDown on focused View, then on Activity, then on the rest. - Michal Chudy

But as far as we are returning false, it will go to the next receiver. Right? Though answer by @MoshErsan may be preferable to do this. But as mentioned in the question, onKeyDown is already overridden in Activity, so you have to return false there, no matter what! :) - Vikram Singh

It's just as you say. By your favor, I could understand about the order in which methods are called. Actually when I tried, it was View#onKeyPreIme,Activity#dispatchKeyEvent, View#dispatchKeyEvent , View#onKeyDown, then lastly, Activity#onKeyDown. ¡Gracias! - Gottie

@Gottie Exactly! It is also worth checking what happens if you have more than one View (f.e. two EditTexts), and one of them has focus. - Michal Chudy

Puedes intentar usar

setFocusableInTouchMode(true)
setFocusable(true)
requestFocus()

on your customview

Respondido 24 Feb 18, 12:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.