AlertDialog OnBackPressed()不能正常工作 [英] AlertDialog OnBackPressed() Not Working Properly

查看:131
本文介绍了AlertDialog OnBackPressed()不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为简单的警告对话框"编写了以下代码,但未显示警告对话框". API:26

I've written the following code for simple Alert Dialog but Alert Dialog doesn't show up. API: 26

 @Override
    public void onBackPressed() {
        super.onBackPressed();

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setMessage("Are You sure to Exit?")
            .setTitle("Exit")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    MainActivity.super.onBackPressed();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });

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

我是android的新手,并且正在测试它的功能. 我已经用30分钟的时间对该小代码进行了调试,并在模拟器和外部电话中使用了不同的电话,但是失败了. 然后,我决定将此代码放到stackoverflow上.

I'm extremely new to android and Testing it's features. I've worked for 30 minutes on this little code to debug it and used different phones in emulator as well as External Phones but failed. Then i decided to put this code on stackoverflow.

推荐答案

使用此代码以编程方式退出或关闭应用程序

Use this code for exit or closing app programically

@Override
    public void onBackPressed() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle("Exit Application?");
        alertDialogBuilder
                .setMessage("Click yes to exit!")
                .setCancelable(false)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                moveTaskToBack(true);
                                android.os.Process.killProcess(android.os.Process.myPid());
                                System.exit(1);
                            }
                        })

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

                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

这篇关于AlertDialog OnBackPressed()不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆