0

我遇到了该方法的语法错误

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

4

2 回答 2

2

试试这个;

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

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

并带走AlertDialog alertDialog = null;它没有用。

下一次,尝试查找该方法是否确实在您尝试调用它的类中。alertDialog是 a AlertDialog,它没有这个方法。这应该会为您敲响警钟,以查找它到底在哪个班级。

于 2013-07-01T07:46:58.710 回答
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();
于 2013-07-01T07:57:13.193 回答