如何显示简单的AlertDialog?

时间:2017-05-26 06:41:51

标签: android android-alertdialog

我正在尝试从班级中显示AlertDialog。程序流程正常,因为我能够正确显示Toast消息。但是,对话框从未出现过?为什么会这样?我没有在日志中收到任何错误消息和/或没有找到应用程序崩溃。这种行为可能是什么原因。

我已获得所需的许可

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

请参阅我的代码:

if (serverApkVersion > localApkVersion) {
    AlertDialog alertDialog = new AlertDialog.Builder(this)
            .setTitle("Title")
            .setMessage("Are you sure?")
            .create();
    alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    alertDialog.show();
    Toast.makeText(context, "toast is working, but dialog is not >:(", Toast.LENGTH_LONG).show();
} else {
    Toast.makeText(context, "up to date!", Toast.LENGTH_LONG).show();
}

4 个答案:

答案 0 :(得分:0)

试试这个

 AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("title");
        builder.setMessage("message");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //do your action
            }
        });       
        builder.setNegativeButton("No", , new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //do your action
            }
        });
        builder.show();

答案 1 :(得分:0)

试试这个简单的例子:

NAME

对于您的代码,您已获得用户的许可。

答案 2 :(得分:0)

enter image description here只需将您的AlertDialog替换为AlertDialog.Builder,就可以了。

if (serverApkVersion > localApkVersion) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(Checking.this)
                    .setTitle("Title")
                    .setMessage("Are you sure?");
                     alertDialog.show();
        Toast.makeText(context, "toast is working, but dialog is not >:(", Toast.LENGTH_LONG).show();
    }else {
        Toast.makeText(context, "up to date!", Toast.LENGTH_LONG).show();
    }

答案 3 :(得分:0)

您的AlertDialog代码似乎没问题。我想问题是你用来创建Context instance的错误AlertDialog.Builder

使用:

AlertDialog alertDialog = new AlertDialog.Builder(context)

代替:

AlertDialog alertDialog = new AlertDialog.Builder(this)

更新您的代码,如下所示:

if (serverApkVersion > localApkVersion) {
    AlertDialog alertDialog = new AlertDialog.Builder(context)
            .setTitle("Title")
            .setMessage("Are you sure?")
            .create();
    alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    alertDialog.show();
    Toast.makeText(context, "toast is working, but dialog is not >:(", Toast.LENGTH_LONG).show();
} else {
    Toast.makeText(context, "up to date!", Toast.LENGTH_LONG).show();
}

仅供参考,如果您的应用在Android 6.0及更高版本上运行,那么您应该为SYSTEM_ALERT_WINDOW添加运行时权限。

有关详细信息,请参阅this

希望这会有所帮助〜