Android应用中的AlertDialog未显示

时间:2014-06-17 14:28:42

标签: android alertdialog

我正在尝试创建一个警告对话框,但在运行我的应用程序时它不会出现。这是我的代码:

final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialog, final int id) {
            startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialog, final int id) {
            dialog.cancel();
            buildLocationMessage();
        }
    });
    final AlertDialog alert = builder.create();
    alert.show();

2 个答案:

答案 0 :(得分:0)

试试这个:

final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);

        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
            }
        });
        alertDialog.show();

只需为“否”添加setButton

答案 1 :(得分:0)

试试这段代码 -

final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

builder.setMessage("Your GPS seems to be disabled,do you want to enable it?");

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) {

//do stuff
startActivity(
     new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
   }
});

builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
        dialog.cancel();
    }
});

AlertDialog alert = builder.create();
alert.show();