如何在android中提示用户使用类似Toast的消息?

时间:2012-03-07 01:17:18

标签: java android eclipse

我希望用户通过向消息和“是”或“否”按钮显示对话来确认操作。如何显示,并根据他们选择的按钮执行操作?

谢谢,AlertDialog看起来像我正在寻找的。但是,有一个错误,它说"AlertDialog.Builder(this);"告诉我,"The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined" -

4 个答案:

答案 0 :(得分:4)

如图所示here

private static final int DIALOG = 1;

显示对话框调用

showDialog(DIALOG);

覆盖onCreateDialog,使用开关检查对话框ID并插入

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure about this?")
   .setCancelable(false)
   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            // whatever if YES
       }
   })
   .setNegativeButton("No", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            // whetever if NO
       }
   });
AlertDialog alert = builder.create();

答案 1 :(得分:3)

您正在寻找的是AlertDialog。使用示例here,您可以轻松创建一个“是/否”对话框,该对话框将显示以下内容:

enter image description here

答案 2 :(得分:1)

您创建一个新的AlertDialog.Builder,传递一些参数,最后调用其create()方法,并将返回值分配给AlertDialog对象以保存对它的引用。

AlertDialog.Builder adb = new AlertDialog.Builder(this);
        adb.setTitle("Question");
        adb.setMessage(Html.fromHtml("Visit Stackoverflow?"));
        adb.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Action for YES
                startActivity(
                         new Intent(
                                Intent.ACTION_VIEW,
                                Uri.parse("http://www.stackoverflow.com")));
                return;
            }
        });

        adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Action for NO
                return;
            }
        });

AlertDialog myDialog = adb.create();

答案 3 :(得分:1)

这很简单,如下所示

new AlertDialog.Builder(this)
            .setTitle("Info")
            .setMessage("hello")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    // Some stuff to do when ok got clicked                 
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    // Some stuff to do when ok got clicked
                }
            })
            .show();