Android method to resolve back events of Activity that cannot be caught when dialog ejects

  • 2020-06-19 11:42:53
  • OfStack

This article shows how Android solves back events that cannot catch Activity when dialog pops up. Share to everybody for everybody reference. The specific analysis is as follows:

In some cases, we need to capture the back key event, and then write the processing we need to do in the captured event. We can usually capture the back event in the following three ways:

1) Override onKeyDown or onKeyUp method

2) Rewrite onBackPressed method

3) Rewrite dispatchKeyEvent method

These 3 kinds of methods have what distinction to do not elaborate here, interested friend can consult relevant data.

However, none of the above methods can capture the back key event when dialog pops up. Because the above method is overwritten in activity, it can capture the corresponding back key event when activity is the current focus, but when dialog pops out, dialog gets the current focus, so the method in activity cannot get back key event. At this time, there are two ways of thinking:

1) Set setOnCancelListener monitoring of dialog:


selectDialog.setOnCancelListener(new OnCancelListener() {
  @Override
  public void onCancel(DialogInterface dialog) {
   // TODO Auto-generated method stub
   // Toast.makeText(getBaseContext(), " Click on the back", Toast.LENGTH_SHORT).show();
  }
});

In this way, the back key event can be caught. When the back key is pressed, the default operation of the system will cause dialog cancel to drop. At this time, OnCancelListener will be triggered.

2) Set setOnKeyListener of dialog to override 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(), " Click on the back", Toast.LENGTH_SHORT).show();
  break;
 default:
  break;
 }
 return super.dispatchKeyEvent(event);
}

Then you can do what you want in dispatchKeyEvent.

Hopefully, this article has been helpful in your Android programming.


Related articles: