2012-03-07 76 views
2

我希望用户通过向他们显示与消息以及“是”或“否”按钮的对话来确认动作。我如何使它显示,并根据他们选择的按钮执行操作?你如何在android中提示用户类似toast的消息?

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

+2

显然......'System.err.println(“你喜欢烤面包吗?”);':-) – 2012-03-07 01:27:54

回答

3

你在找什么是AlertDialog。使用示例here,您可以轻松创建一个是/否对话框,看起来会沿着线:您创建一个新的AlertDialog.Builder

enter image description here

1

,它传递一些参数,最后调用它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(); 
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

这很简单如下所示

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();