Anyway, while working on an Android app, I came across a small problem that really annoyed me. I was displaying a modal dialog and I did not want the user to navigate away from the modal dialog unless they clicked an 'OK' button.
But then I saw a problem. All the user had to do was press either the back button, the home button or the call buttons and the dialog disappeared. Now that is not what I intended or wanted and in the interest of self preservation, I started wondering how to solve the problem and thankfully found a very easy solution.
All I had to do was consume the keydown events for those buttons by overriding the onKeyDown method in my dialog class.
@OvverideThat is it. I could now prevent users from clicking on these buttons and navigating away from the dialog.
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
return true;
case KeyEvent.KEYCODE_CALL:
return true;
case KeyEvent.KEYCODE_DPAD_CENTER :
return true;
case KeyEvent.KEYCODE_ENDCALL
return true;
case KeyEvent.KEYCODE_HOME: // this does not work.
return true;
default:
break;
}
// pass all unhandled events to the parent class
return super.onKeyDown(keyCode, event);
}
This can be used to disable users from pressing any other buttons you don't want them to. The only exception is the 'Home' button. I am not sure if there is any other way, but this approach certainly does not work. You can find a more detailed reference on all available key event constants here.