In some cases, we need to capture the back key event and then write the processing we need to do in the captured event, usually in the following three ways to capture the back event:
1) rewrite the onkeydown or OnKeyUp method
2) Overriding the Onbackpressed method
3) Overriding the Dispatchkeyevent method
The difference between these three ways is not elaborated here, interested friends can consult the relevant information.
However, when there is a dialog pop-up, want to capture the back key event, the above three methods can not be achieved. Because the above method is rewritten in the activity, that is, when the activity is the current focus, it can catch the corresponding back key event, and when the dialog pops up, dialog gets the current focus, So the method inside the activity can't get to the back key event, there are two kinds of ideas:
1) Set the dialog Setoncancellistener monitor:
Selectdialog.setoncancellistener (New Oncancellistener () {
@Override
public void OnCancel (Dialoginterface dialog) {
TODO auto-generated Method Stub
Toast.maketext (Getbasecontext (), "clicked Back", Toast.length_short). Show ();
}
});
This allows you to capture the back key event, when you press back key, the system default action will let dialog cancel, this will trigger the Oncancellistener, and then in the OnCancel method can implement the action you want to achieve.
2) Set the dialog Setonkeylistener and override the Dispatchkeyevent method
Selectdialog.setonkeylistener (New Onkeylistener () {
@Override
public boolean OnKey (dialoginterface dialog, int keycode, keyevent event) {
TODO auto-generated Method Stub
if (keycode = = Keyevent.keycode_back && event.getrepeatcount () ==0)
{
Dialog.dismiss ();
}
return false;
}
});
public boolean dispatchkeyevent (KeyEvent event)
{
Switch (Event.getkeycode ())
{
Case Keyevent.keycode_back:
Toast.maketext (Getbasecontext (), "clicked Back", Toast.length_short). Show ();
Break
Default
Break
}
Return Super.dispatchkeyevent (event);
}
Then you can do what you want to do in dispatchkeyevent.
Reprint: How Android resolves a back event that cannot capture activity when dialog pops up