Reputation: 110550
I have implementation onBackPressed()
, it works when there is no popup alert dialog from my activity. But when my activity pops up a dialog, onBackPressed()
never get called.
public void onBackPressed() {
super.onBackPressed();
// more implementation.
}
How can I detect back key is pressed by user when a dialog is pop up?
Thank you.
Upvotes: 2
Views: 5138
Reputation: 3667
You could also create your own custom Pop-up message class which extends AlertDialog.Builder, and handle the user selection on the pop-up window (i.e. Yes/No, Submit/Cancel buttons) using a Java Interface.
That's the way I did it, so I could handle warnings and errors, other alerts using my own custom alert pop-up message window.
I didn't have to do anything special in the custom Pop-up message class to handle the back-button being pressed.
However, I did handle the back-button being pressed in the activity class that calls my custom pop-up message class.
/**
* onKeyDown method
*
* Executes code depending on what keyCode is pressed.
*
* @param int keyCode
* @param KeyEvent
* event KeyEvent object
*
* @return true if the code completes execution, false otherwise
*
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
//handle the back-key press here
default:
return false;
}
}// end onKeyDown
Upvotes: 0
Reputation: 69198
Well, in that case Dialog#onBackPressed() will be called, which is expected behavior.
Upvotes: 2
Reputation: 156
Something like this, should do the job.
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
yourpopup.dismiss(); // or whatever you want todo here
return true;
}
return super.onKeyDown(keyCode, event);
}
Upvotes: 2
Reputation: 30825
That's because your Activity doesn't have focus at that point. You'll have to add a button listener to the dialog that pops up.
Upvotes: 0