Reputation: 5795
First case
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Second case
OnBackPressed();
Which case is better to override backKeypress event?
Upvotes: 2
Views: 1773
Reputation: 5258
If you want to catch the back press prior to 2.0, you can use the onKeyDown
method like so:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//Do something on back press
}
return super.onKeyDown(keyCode, event);
}
Interestingly, if you override both the onBackPressed and onKeyDown, both will catch the back press with onKeyDown
catching it first.
If you call super.onKeyDown
in onKeyDown
like we are above, then the onBackPressed
method will fire. If you do not call super.onKeyDown
then onBackPressed
will never be called.
Unless you have a specific reason to target below 2.0, there isn’t much of a reason to bother.
Upvotes: 4
Reputation: 3123
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
If you are talking overriding this event the first one is the right thing to implement.
Upvotes: 1
Reputation: 4119
I think that you should use:
@Override
public void onBackPressed() {
//...
}
in case when you just want to override an event. The first method is better if you want to detect that user physically clicked back key.
Upvotes: 2