How Android solves the back event that dialog cannot capture activity when it pops up
In some cases, we need to capture the back key event, and then write to what we need to do in the event we capture, usually with the following three ways to catch the back event:
1) Rewrite onkeydown or OnKeyUp method
2) Rewrite the onbackpressed method
3) Rewrite the Dispatchkeyevent method
What's the difference between these three ways? No elaboration is made here, and interested friends can consult the relevant information.
However, when there is a dialog pop-up, want to capture the Back button event, the above three methods can not be achieved. Because the above method is rewritten in the activity, that is, when the active 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 cannot get the back key event, and there are two ways to do this:
1) Set dialog Setoncancellistener monitoring:
Selectdialog.setoncancellistener (New Oncancellistener () {
@Override public
void OnCancel (dialoginterface Dialog) {
//TODO auto-generated Method Stub
//Toast.maketext (Getbasecontext (), "Click Back", Toast.length_short ). Show ();
}
};
This allows you to catch the event of the back key, when you press back key, the system default operation will let dialog cancel, this time will trigger Oncancellistener, and then in OnCancel method inside can realize oneself want to achieve the operation.
2 Set the dialog setonkeylistener and rewrite 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 && E Vent.getrepeatcount () ==0)
{
Dialog.dismiss ();
}
return false;
}
});
public boolean dispatchkeyevent (KeyEvent event)
{
switch (Event.getkeycode ())
{
case Keyevent.keycode_back:
toast.maketext (Getbasecontext (), "Click Back", Toast.length_short). Show ();
break;
Default: Break
;
}
Return Super.dispatchkeyevent (event);
}
Then in the dispatchkeyevent inside can realize oneself want to implement the operation.
Thank you for reading, I hope to help you, thank you for your support for this site!