使用自定义按钮关闭带有自定义界面的警报对话框

Dismissing Alert Dialog with custom interface using custom button

我有一个自定义警报对话框。我目前正在尝试更改我的两个按钮的 onclicklisteners。以前我使用过以下代码。

builder.setNegativeButton("Nope", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // Do nothing
            dialog.dismiss();
        }
    });
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) { 
           \code here which is not relevant to question 
      }
    });

但是,现在由于对话框具有自定义视图和自定义按钮,所以我使用以下方法。

Button confirm = (Button) windowView.findViewById(R.id.confirmbutton);
     Button cancel = (Button) windowView.findViewById(R.id.negatebutton);

     cancel.setOnClickListener(new Button.OnClickListener() {

         public void onClick(View v){

         }

     });

我的问题是,如果无法访问 dialog 变量,如何关闭取消按钮侦听器中的对话框。我想使用我已经在使用的 AlertDialog 并且不想要具有不同类型对话框的解决方案。

你需要做的,就是保留一个Dialog的引用,然后你就可以调用dismiss方法了。在我的示例中,我将引用保留为 属性.

private Dialog dialog;

@Override
public void onResume() {

    AlertDialog.Builder adb = new AlertDialog.Builder(this);

    LinearLayout llView = new LinearLayout(this);

    Button btnDismiss = new Button(this);
    btnDismiss.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    llView.addView(btnDismiss);

    adb.setView(llView);
    dialog = adb.create();
    dialog.show();

    super.onResume();
}

将引用保持为 属性 很重要,因为引用必须是最终的才能在 onClick 方法中访问,并且由于尚未创建对话框,因此您不能将最终引用保留在方法中变量,然后将其保存在 属性.