我有一个正在使用主题的活动。对话框样式,使其成为另一个活动上方的浮动窗口。但是,当我在对话框窗口外(在后台活动上)单击时,对话框关闭。我怎样才能阻止这种行为?


当前回答

将对话框可取消设置为false就足够了,并且您可以在警报对话框外触摸或单击后退按钮将使警报对话框消失。所以就用这个吧:

setCancelable(假)

另一个函数不再需要了: dialog.setCanceledOnTouchOutside(假);

如果你正在创建一个临时对话框,并想把这行代码放在那里,下面是一个例子:

new AlertDialog.Builder(this)
                        .setTitle("Trial Version")
                        .setCancelable(false)
                        .setMessage("You are using trial version!")
                        .setIcon(R.drawable.time_left)
                        .setPositiveButton(android.R.string.yes, null).show();

其他回答

你实际上有一个活动(即使它看起来像一个对话框),因此你应该调用setFinishOnTouchOutside(false)从你的活动,如果你想保持它打开时,后台活动被单击。

编辑:这只适用于android API级别11或更高

对于更高的API 10,对话框在外部触摸时消失,而在低于API 11的情况下,对话框不会消失。为了防止这种情况,你需要做到:

xml: <项目名称=“android: windowcloseonteutside”>false</项目>

OR

在onCreate()方法中,使用:this.setFinishOnTouchOutside(false);

注:对于API 10及以下,此方法无效,也不需要。

对我来说有用的是创建DialogFragment并将其设置为不可取消:

dialog.setCancelable(false);
Dialog dialog = new Dialog(context)
dialog.setCanceledOnTouchOutside(true); 
//use this to dismiss the dialog on outside click of dialog

dialog.setCanceledOnTouchOutside(false);
//use this for not to dismiss the dialog on outside click of dialog.

观看这个链接了解更多关于对话的细节。

dialog.setCancelable(false);
//used to prevent the dismiss of dialog on backpress of that activity

dialog.setCancelable(true);
//used to dismiss the dialog on onbackpressed of that activity

以下是我的解决方案:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select The Difficulty Level");
builder.setCancelable(false);