Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get onBackPressed event inside a custom ViewGroup?

I am creating a custom Android component that needs sometimes to consume the onBackPressed event (e.g. there's a popup menu inside the custom ViewGroup, if it's showing, the back button event closes it and is consumed, otherwise it's ignored). Is that possible? Can I intercept this event from inside my ViewGroup subclass and how?

Edit: I tried overriding onKeyPreIme as the Android documentation implies, the method is never invoked from within ViewGroup.

@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event)
{
     return true;
}

In the onKeyPreIme documentation it says:

Handle a key event before it is processed by any input method associated with the view hierarchy. This can be used to intercept key events in special situations before the IME consumes them; a typical example would be handling the BACK key to update the application's UI instead of allowing the IME to see it and close itself.

like image 958
Francois Zard Avatar asked Nov 22 '25 16:11

Francois Zard


1 Answers

The reason why onKeyDown or onKeyPreIme are never invoked is because the ViewGroup does not have focus.

The solution was to request focus in the ViewGroup subclass' constructor:

this.setFocusable(true);
this.setFocusableInTouchMode(true);
this.requestFocus();
like image 196
Francois Zard Avatar answered Nov 25 '25 04:11

Francois Zard