Android 5 秒后关闭对话框?

新手上路,请多包涵

我正在开发一个辅助功能应用程序。当用户想要离开应用程序时,我会显示一个对话框,他必须在其中确认他想离开,如果他在 5 秒后没有确认,对话框应该自动关闭(因为用户可能不小心打开了它)。这类似于在 Windows 上更改屏幕分辨率时发生的情况(出现警告,如果您不确认,它将恢复为之前的配置)。

这就是我显示对话框的方式:

 AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Leaving launcher").setMessage("Are you sure you want to leave the launcher?");
            dialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int whichButton) {
                    exitLauncher();
                }
            });
            dialog.create().show();

如何在显示 5 秒后关闭对话框?

原文由 lisovaccaro 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 768
2 个回答
final AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Leaving launcher").setMessage("Are you sure you want to leave the launcher?");
dialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int whichButton) {
        exitLauncher();
    }
});
final AlertDialog alert = dialog.create();
alert.show();

// Hide after some seconds
final Handler handler  = new Handler();
final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        if (alert.isShowing()) {
            alert.dismiss();
        }
    }
};

alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
    @Override
    public void onDismiss(DialogInterface dialog) {
        handler.removeCallbacks(runnable);
    }
});

handler.postDelayed(runnable, 10000);

原文由 Vladimir Mironov 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 CountDownTimer 来实现。

       final AlertDialog.Builder dialog = new AlertDialog.Builder(this)
            .setTitle("Leaving launcher").setMessage(
                    "Are you sure you want to leave the launcher?");
       dialog.setPositiveButton("Confirm",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int whichButton) {
                     exitLauncher();

                }
            });
    final AlertDialog alert = dialog.create();
    alert.show();

    new CountDownTimer(5000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub

            alert.dismiss();
        }
    }.start();

原文由 moDev 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题