如何在android中正确添加消息框

时间:2013-07-01 07:41:30

标签: android eclipse

我遇到了方法

的语法错误
setPositiveButton(String, new DialogInterface.OnClickListener(){}) : is undefined for the type AlertDialog

如何解决?


AlertDialog alertDialog = null;
alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("error msg");
alertDialog.setMessage("You should register before");
alertDialog.setCancelable(true);
alertDialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog  
 }
}); 

alertDialog.show();

2 个答案:

答案 0 :(得分:2)

试试这个;

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

然后,在完成所有设置后,执行.create();

带走AlertDialog alertDialog = null;没有用。

下次,尝试查看该方法是否实际上在您尝试调用它的类中。 alertDialogAlertDialog,没有此方法。这应该响铃,你可以找到它确切的类。

答案 1 :(得分:0)

AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                        this);
alertDialog.setTitle("error msg");
                alertDialog.setPositiveButton("OK", this);
                alertDialog.setNegativeButton("Cancel", this);
                alertDialog
                        .setMessage("You should register before");
                alertDialog.show();

你应该实现DialogInterface.OnClickListene 例如:

public class MainActivity extends Activity implements
        DialogInterface.OnClickListener{}

然后你将获得覆盖方法OnClick。

    public void onClick(DialogInterface dialog, int which) {
            if (which == Dialog.BUTTON_POSITIVE) {
                        //do what ever you want on OK click
            } else if (which == Dialog.BUTTON_NEGATIVE) {
                        //do what ever you want on Cancel click

            }
        }

如果您只想使用消息框

AlertDialog.Builder alertDialog = new AlertDialog.Builder(context).create();
                alertDialog.setMessage("You should register before");
                alertDialog.setButton("Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // here you can add functions
                            }
                        });
                // alertDialog.setIcon(R.drawable.icon);
                alertDialog.show();