防止后退按钮关闭对话框 [英] Prevent back button from closing a dialog box

查看:112
本文介绍了防止后退按钮关闭对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图防止在Android中按下后退"按钮时关闭AlertDialog框.我在此线程中使用了两种流行的方法 ,并使用了System.out.我可以看到在两种情况下都可以执行代码.但是,后退按钮 still 会关闭对话框.

I am trying to prevent an AlertDialog box from closing when pressing the back button in Android. I have followed both of the popular methods in this thread, and with System.out.println I can see that in both cases the code executes. However, the back button still closes the dialog box.

我可能做错了什么?最终,我试图防止后退按钮关闭对话框-这是在应用程序首次运行时显示的免责声明,我不希望用户有任何选择,只能在其中按下接受"按钮.以便该应用继续运行.

What could I be doing wrong? Ultimately I'm trying to prevent the back button closing a dialog box - it is a disclaimer that is displayed the first time the app is run and I don't want the user to have any option but to press the "Accept" button in order for the app to continue.

推荐答案

只需使用

Simply use the setCancelable() feature:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);

这可以防止后退"按钮关闭对话框,但是如果您选择使用它,则使负"按钮保持原样.

This prevents the back button from closing the dialog, but leaves the "negative" button intact if you chose to use it.

根据Squonk的评论,任何不想接受您的服务条款的用户都可以按主页"按钮,这里还有两种防止他们退出"用户协议的方法.一个是简单的拒绝"按钮,另一个是覆盖对话框中的后退按钮:

While any user that does not want to accept your terms of service can push the home button, in light of Squonk's comment, here two more ways to prevent them from "backing out" of the user agreement. One is a simple "Refuse" button and the other overrides the back button in the dialog:

builder.setNegativeButton("Refuse", new OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {
               finish();
           }
       })
       .setOnKeyListener(new OnKeyListener() {
           @Override
           public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
               if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
                   finish();
               return false;
           }
       });

这篇关于防止后退按钮关闭对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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