2

I have a webView inside an Activity's layout. If back button is pressed, I want that view to disappear and other views to become visible, to I did the following:

    @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && web.getVisibility()==View.VISIBLE) {
        restoreInitalState(); // set Visibility of Views
        APP_CONSTANTS.LOGIN_OP_CANCELLED(getApplicationContext()); // inform the user that the current operation was cancelled
    }
    return super.onKeyDown(keyCode, event);

}

it works BUT it finishes the Activity immediately after calling my methods, like if the back button was pressed 2 times. I need to keep the current Activity and just call my methods mentioned above. Any suggestions?

Droidman
  • 11,485
  • 17
  • 93
  • 141

4 Answers4

3

You need to return false. Change this:

if (keyCode == KeyEvent.KEYCODE_BACK && web.getVisibility()==View.VISIBLE) {
    restoreInitalState(); // set Visibility of Views
    APP_CONSTANTS.LOGIN_OP_CANCELLED(getApplicationContext()); // inform the user that the current operation was cancelled
}

to this:

if (keyCode == KeyEvent.KEYCODE_BACK && web.getVisibility()==View.VISIBLE) {
    restoreInitalState(); // set Visibility of Views
    APP_CONSTANTS.LOGIN_OP_CANCELLED(getApplicationContext()); // inform the user that the current operation was cancelled
    return false;
}
Adam Brill
  • 330
  • 1
  • 5
1

I think the correct method is:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && web.getVisibility()==View.VISIBLE) {
        restoreInitalState(); // set Visibility of Views
        APP_CONSTANTS.LOGIN_OP_CANCELLED(getApplicationContext()); 
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
dmaxi
  • 3,267
  • 1
  • 18
  • 15
1

Or just use the method, onBackPressed() in youe Activity class ,that's the simplest way to Override it.

AbdulHannan
  • 358
  • 1
  • 15
1

I think the callback method you are looking for is onBackPressed.

But your current solution should work as well, you just need to return true inside your if-block otherwise the event will be propagated to another callback.

Emil
  • 7,220
  • 17
  • 76
  • 135
Exoit
  • 76
  • 3