.dismiss()在AlertDialog中显示错误

时间:2013-08-05 15:11:58

标签: java android android-alertdialog

我有以下代码:

            AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.displayfilecontents, null);
            EditText text = (EditText) view.findViewById(R.id.etFileContents);
            if (text != null) {
                text.setFocusable(false);
                text.setLongClickable(false);
                text.setTextIsSelectable(false);
            }
            text.setText(builder);
            b.setView(view);
            b.setTitle("Trip Name: " + FilesInFolder.get(position).toString().substring(0, FilesInFolder.get(position).toString().lastIndexOf(".")));
            Button btnCloseIt = (Button) view.findViewById(R.id.btnClose);
            btnCloseIt.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    b.dismiss();
                }
            });
            AlertDialog dl = b.create();
            dl.show();

按下btnCloseIt后,我试图关闭对话框。我在这一行收到错误:

b.dismiss(); //giving an error

错误:The method dismiss() is undefined for the type AlertDialog.Builder

更新:[已解决]

        // custom dialog
        final Dialog dialog = new Dialog(getActivity());
        dialog.setContentView(R.layout.displayfilecontents);
        dialog.setTitle("Trip Name: " + FilesInFolder.get(position).toString().substring(0, FilesInFolder.get(position).toString().lastIndexOf(".")));

        EditText text = (EditText) dialog.findViewById(R.id.etFileContents);
        if (text != null) {
            text.setFocusable(false);
            text.setLongClickable(false);
            text.setTextIsSelectable(false);
        }
        text.setText(builder);
        Button btnCloseIt = (Button) dialog.findViewById(R.id.btnClose);
        // if button is clicked, close the custom dialog
        btnCloseIt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();

2 个答案:

答案 0 :(得分:2)

正如其他人已经指出的那样,b是对AlertDialog.Builder的引用,而不是对Dialog本身的引用。 AlertDialog.Builder类没有任何名为dismiss()的方法。当您从Dialog课程中调用create()show()方法时,请保存对您返回的AlertDialog.Builder的引用。

还有一件事,因为你同时调用create()show()方法,你真的想调用这两种方法吗?我相信在这里只调用show()方法就足够了。来自开发人员参考public AlertDialog show () : Creates a AlertDialog with the arguments supplied to this builder and show()'s the dialog.

答案 1 :(得分:1)

您需要存储调用b.create()的结果;这就是你需要致电dismiss()