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


当前回答

以下是我的解决方案:

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

其他回答

在jetpack组合中,使用遣散onclickoutside = false属性来防止关闭。

    AlertDialog(
        title = {
            Text("Title")
        },
        text = {
            Text(text = name)
        },
        onDismissRequest = onDismiss,
        confirmButton = {
            TextButton(onClick = onDismiss ) {
                Text("Yes")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss ) {
                Text("Cancel")
            }
        },
        properties = DialogProperties(
            dismissOnClickOutside = false
        )
    )

}

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

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

OR

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

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

也可以分配不同的动作实现onCancelListener:

alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){                   
    @Override
    public void onCancel(DialogInterface dialogInterface) {
        //Your custom logic
    } 
});

对于API > 11使用setFinishOnTouchOutside(false),不要担心,因为它是android的默认行为,活动主题对话框不会在API < 11的外部触摸中完成:)!!

这对你有帮助。它是处理touch outside事件的一种方式:

如何取消一个对话主题,如活动时触摸窗外?

通过捕捉事件,什么都不做,我认为你可以阻止关闭。但奇怪的是,你的活动对话框的默认行为应该是当你触摸外部时不关闭自己。

(PS:代码使用WindowManager.LayoutParams)