在onCreateDialog()中销毁DialogFragment

6

我有一个对话框片段,它初始化Google Plus视图,有时这些视图会失败,因此我想在显示给用户之前在该点处终止对话框。

我应该如何结束对话框创建过程?从返回Dialog对象的onCreateDialog中返回null会导致程序崩溃。

3个回答

6
如果您想在onCreateDialog中关闭DialogFragment,可以按照以下步骤进行操作:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    setShowsDialog(false);
    dismiss();
    return null;
}

无需覆盖onActivityCreated()方法。

1
我建议返回一个新的Dialog()而不是null,因为在某些系统上我遇到了NPE问题。但总的来说,是的,那也是一种解决方案。 - Aviran
无法返回 null,因为结果必须是非 null:https://developer.android.com/reference/androidx/fragment/app/DialogFragment?hl=en#onCreateDialog(android.os.Bundle)。此外,即使返回非 null 对话框,仍会为我显示一个透明层。对我而言,这个解决方案有效:https://dev59.com/b3TYa4cB1Zd3GeqPzNOS#69141205。 - android developer

3
使用 onActivityCreated() Fragment 回调函数解决了此问题,该函数在 OnCreateDialog() 后被调用。我从 onCreateDialog() 返回一个有效的 Dialog,但使用 dismiss 标记应该关闭对话框。
public void onActivityCreated (Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if(dismiss) {
        this.dismiss();
    }
}

2
我成功地通过在onCreateDialog()中调用dismiss()来完成了这个。 - Johnny Z
可以工作,但已被弃用:对于涉及片段视图的代码,请使用onViewCreated(View,Bundle),对于其他初始化,请使用onCreate(Bundle)。要在片段活动的Activity.onCreate(Bundle)调用时获取特定的回调,请在onAttach(Context)中在Activity的生命周期上注册androidx.lifecycle.LifecycleObserver,并在接收到Lifecycle.State.CREATED回调时将其删除。 https://developer.android.com/reference/androidx/fragment/app/Fragment#onActivityCreated(android.os.Bundle) 。我已经创建了一个更更新的答案:https://dev59.com/b3TYa4cB1Zd3GeqPzNOS#69141205 - android developer

0

其他答案有点过时,其中一个对我也没用(我在那里写了我的评论),所以这是我认为最新和有效的方法:

onCreateDialog回调中,编写成功时的逻辑。如果失败,则返回一些默认对话框(无论如何都不会使用),同时添加到生命周期的onStart回调中以关闭DialogFragment(使用dismissdismissAllowingStateLoss):

fun Lifecycle.runOnStarted(runnable: () -> Unit) {
    addObserver(object : DefaultLifecycleObserver {
        override fun onStart(owner: LifecycleOwner) {
            super.onStart(owner)
            runnable.invoke()
        }
    })
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    //create the builder of the dialog, and then check if need to dismiss
    if (needToDismiss) {
        lifecycle.runOnStarted{
            dismissAllowingStateLoss()
        }
        return builder.create()
    }

另一种方法是使用Kotlin协程,而不使用我创建的辅助函数:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    //create the builder of the dialog, and then check if need to dismiss
    if (needToDismiss) {
        lifecycleScope.launch {
            whenStarted {
                dismissAllowingStateLoss()
            }
        }
        return builder.create()
    }

或者您可以使用这个帮助函数,它使用 Kotlin 协程使代码更简洁:

fun LifecycleOwner.runOnStarted(runnable: () -> Unit) {
    lifecycleScope.launch {
        whenStarted{
            runnable.invoke()
        }
    }
}

使用方法与以前一样简单:

runOnStarted{
    dismissAllowingStateLoss()
}

请注意,我使用 onStart 回调而不是 onCreate。原因是对于某些情况,onStart 起作用,而 onCreate 不起作用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接