需要在Android中创建AlertDialog的建议

时间:2011-10-01 16:56:44

标签: android alertdialog

在我的活动中按下按钮时,我调用了以下代码。

AlertDialog.Builder alertDialog = new AlertDialog.Builder(this).create();  
            alertDialog.setTitle("Alert 1");  
            alertDialog.setMessage("This is an alert");  
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {  
              public void onClick(DialogInterface dialog, int which) {  
                return;  
            } });  

我已经添加了这两个进口:

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;

但仍然会出现以下错误:

Description Resource    Path    Location    Type
The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined  MobileTrackerActivity.java  /MobileTracker/src/com/example/mobiletracker    line 77 Java Problem
The method setButton(String, new DialogInterface.OnClickListener(){}) is undefined for the type AlertDialog.Builder MobileTrackerActivity.java  /MobileTracker/src/com/example/mobiletracker    line 80 Java Problem
Type mismatch: cannot convert from AlertDialog to AlertDialog.Builder   MobileTrackerActivity.java  /MobileTracker/src/com/example/mobiletracker    line 77 Java Problem

有人可以给我任何解决方案吗?我是Java的新手。

2 个答案:

答案 0 :(得分:3)

以这种方式创建AlertDilog:

   AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);  
   alertDialog.setTitle("Alert 1");  
   alertDialog.setMessage("This is an alert");  
   alertDialog.setButton("OK", new DialogInterface.OnClickListener() {  
   public void onClick(DialogInterface dialog, int which) {  
        return;  
   } });  
   AlertDialog alert = alertDialog.create();
   alert.show();

答案 1 :(得分:1)

如果你看这个页面:

http://developer.android.com/guide/topics/ui/dialogs.html

并且您获得的错误消息只需进行此更改:

AlertDialog alertDialog = new AlertDialog.Builder(this).create();