首页 > 解决方案 > 可以询问您“是否要关闭它”的退出按钮?

问题描述

我是java的初学者,我有一个问题要问你你知道如何创建退出按钮吗?这个按钮可以在我关闭应用程序之前问我“你想关闭这个应用程序吗?或者”你确定要关闭它吗?“我需要为我的项目做这件事,我需要帮助。请给我一些代码。

标签: javaandroid

解决方案


您的问题非常广泛,但是,您正在寻找一个 AlertDialog ,这是实现:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    MyActivity.this.finish();
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();

推荐阅读