What I’m trying to do is intercept the Back button press from an external Class like this:
public class AnswerView extends RelativeLayout {
public AnswerView(Context context) {
super(context);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
Log.i("AlleAntwoorden", "Back button pressed!");
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I’m adding it like this from my main Activity:
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
mainLayout.addView(new AnswerView(this));
In order for a View to receive any event it needs to have focus. I don’t see any XML, so let’s add a couple characteristics at run time:
Now your layout will intercept the back button in your
OnKeyListener. But if another View has focus, even a child View, the event might be consumed by the child first.To understand this, add an EditText to your AnswerView:
If you click the back button while the EditText has focus: the first click closes the soft keyboard, the second click will finish the current Activity like normal. The
OnKeyListenerevent is not passed up through the View hierarchy by default.