Android:如何在AlertDialog中覆盖onBackPressed()?

时间:2011-10-18 03:06:46

标签: android override android-dialog

我有AlertDialog dlgDetails从另一个AlertDialog dlgMenu显示。如果用户按下dlgDetails中的后退按钮,我希望能够再次显示dlgMenu,如果他按下对话框,则只需退出对话框。

我认为最好的方法是覆盖dlgDetails的onBackPressed,但我不知道如何做到这一点,因为必须使用Builder间接创建AlertDialogs。

我正在尝试创建派生的AlertDialog(public class AlertDialogDetails extends AlertDialog { ...}),但我想我还必须在该类中扩展AlertDialog.Builder以返回AlertDialogDetails,但是不是更简单的方法吗?如果没有,你会如何重写生成器?

4 个答案:

答案 0 :(得分:58)

我最后在我的对话框中添加了一个关键监听器来监听Back键。 不像覆盖onBackPressed()那样优雅,但它有效。 这是代码:

dlgDetails = new AlertDialog.Builder(this)
    .setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey (DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && 
                event.getAction() == KeyEvent.ACTION_UP && 
                !event.isCanceled()) {
                dialog.cancel();
                showDialog(DIALOG_MENU);
                return true;
            }
            return false;
        }
    })
    //(Rest of the .stuff ...)

答案 1 :(得分:5)

找到一个更短的解决方案:)试试这个:

         accountDialog = builder.create();

        accountDialog.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
                activity.finish();

            }
        });

答案 2 :(得分:1)

这会处理BACK按钮和单击OUTSIDE对话框:

yourBuilder.setOnCancelListener(new OnCancelListener() {
    @Override
    public void onCancel(DialogInterface dialog) {
        dialog.cancel();
        // do your stuff...
    }
});

dialog.cancel()是关键:使用dialog.dismiss()这将只处理对话框外的点击,如上所述。

答案 3 :(得分:0)

我在java类中创建了一个新函数,并从对话框Builder的onClick方法调用该函数。

public class Filename extends Activity(){

@Override
onCreate(){
 //your stuff
 //some button click launches Alertdialog
}

public void myCustomDialog(){
 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
 //other details for builder
      alertDialogBuilder.setNegativeButton("BACK",
            new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
                         dialod.dismiss;
                         myCustomBack();
                    }
      });

 AlertDialog alertDialog = alertDialogBuilder.create();
 alertDialog.setCanceledOnTouchOutside(true);
 alertDialog.show();
}

public void myCustomBack(){
  if(condition1){
    super.onBackPressed();
  }
  if(condition 2){
    //do  stuff here
  }
}

@Override
public void onBackPressed(){
  //handle case here
  if (condition A)
    //Do this
  else 
    //Do that
}

}