【问题标题】:Dismissing Alert Dialog with custom interface using custom button使用自定义按钮关闭带有自定义界面的警报对话框
【发布时间】:2015-08-27 20:54:18
【问题描述】:

我有一个自定义警报对话框。我目前正在尝试更改我的两个按钮的 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,并且不想要具有不同类型对话框的解决方案。

【问题讨论】:

    标签: java android customization onclicklistener android-alertdialog


    【解决方案1】:

    你需要做的,只是保留一个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 方法中访问,并且由于尚未创建对话框,因此您不能将最终引用保留在方法变量中,然后将其保留在一个属性。

    【讨论】:

      猜你喜欢
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多