26

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

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

我正在尝试创建一个派生的 AlertDialog ( public class AlertDialogDetails extends AlertDialog { ...}),但我想我还必须AlertDialog.Builder在该类中扩展以返回一个 AlertDialogDetails,但没有更简单的方法吗?如果没有,您将如何覆盖 Builder?

4

4 回答 4

64

我终于在我的对话框中添加了一个键监听器来监听 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 ...)

对于 Kotlin 中的答案,请参见此处:Not working onbackpressed when setcancelable of alertdialog 为 false

于 2011-10-19T00:37:31.383 回答
7

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

         accountDialog = builder.create();

        accountDialog.setOnCancelListener(new OnCancelListener() {

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

            }
        });
于 2013-04-27T10:51:24.760 回答
1

这将同时处理 BACK 按钮和对话框外的单击:

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

dialog.cancel()是关键:dialog.dismiss()正如上面回答的那样,这只会处理对话框外的点击。

于 2013-10-08T10:05:49.773 回答
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
}

}
于 2014-06-02T07:32:26.467 回答