views:

57

answers:

2

I'm writing an application which will have two Activities, when the user presses the back button on the second activity a dialog should pop up asking the user to confirm the action. So how do I intercept this? I seriously doubt about this coz the backstack is a part of the OS itself. Has anyone found a workaround?

+3  A: 

Simply override the onKeyDown method in your activity and look for the back button. Return true so that the event is consumed.

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        //Do something here
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
skorulis
+1, I've done this before and it definitely works although when I used it, it was before I understood the notion of multiple activities...
Chris Thompson
//Do somethings here (I'm trying to display a toast for my test code) is not working for me. And when I press the back button nothing happens.
Ragunath Jawahar
My mistake, I didn't call Toast.show().Working code. Thanx @skorulis
Ragunath Jawahar
+1  A: 

In an activity you can just override

onBackPressed()

edit: that is api lvl 5+ :/ for 4 and below you gotta override onKeyDown()

schwiz
Nice, thanks @schwiz
Ragunath Jawahar