Darpan
Darpan

Reputation: 5795

Which method is preferred to override onBackPressed?

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

Answers (4)

moDev
moDev

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

Ariel Magbanua
Ariel Magbanua

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

Timmetje
Timmetje

Reputation: 7694

You should use:

    @Override
    public void onBackPressed() {

    }

Upvotes: 0

Michał Z.
Michał Z.

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

Related Questions