如何正确关闭 DialogFragment? [英] How to correctly dismiss a DialogFragment?

查看:98
本文介绍了如何正确关闭 DialogFragment?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档对 Dialog 类中的 dismiss() 方法是这样说的:

The docs say this for the dismiss() method from the Dialog class:

关闭此对话框,将其从屏幕上移除.可以调用这个方法安全地从任何线程.请注意,您不应该覆盖此方法来执行关闭对话框时进行清理,而是在 onStop() 中实现.

Dismiss this dialog, removing it from the screen. This method can be invoked safely from any thread. Note that you should not override this method to do cleanup when the dialog is dismissed, instead implement that in onStop().

在我的代码中,我所做的就是调用 getDialog().dismiss() 来关闭它.但我没有做任何其他事情,甚至没有使用 onStop().所以我问的是如何正确地关闭 DialogFragment 以避免任何内存泄漏等.

In my code, all I do is call getDialog().dismiss() to dismiss it. But I am not doing anything else or even using onStop(). So I am asking exactly how to correctly dismiss a DialogFragment to avoid any memory leaks, etc..

推荐答案

tl;dr: 关闭 DialogFragment 的正确方法是使用 dismiss() 直接在DialogFragment上.

tl;dr: The correct way to close a DialogFragment is to use dismiss() directly on the DialogFragment.

详细信息:DialogFragment 的文档 状态

Details: The documentation of DialogFragment states

对话框的控制(决定何时显示、隐藏、关闭)应该通过这里的 API 来完成,而不是直接调用对话框.

Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.

因此,您不应使用 getDialog().dismiss(),因为这会在对话框中调用 dismiss() .相反,您应该使用 DialogFragment 本身的 dismiss() 方法:

Thus, you should not use getDialog().dismiss(), since that would invoke dismiss() on the dialog. Instead, you should use the dismiss() method of the DialogFragment itself:

公共无效解雇()

关闭片段及其对话框.如果片段被添加到后退堆栈,则直到并包括此条目的所有后退堆栈状态都将被弹出.否则,将提交一个新事务以删除该片段.

Dismiss the fragment and its dialog. If the fragment was added to the back stack, all back stack state up to and including this entry will be popped. Otherwise, a new transaction will be committed to remove the fragment.

如您所见,这不仅负责关闭对话框,还负责处理流程中涉及的片段事务.

As you can see, this takes care not only of closing the dialog but also of handling the fragment transactions involved in the process.

如果您明确创建了任何需要手动清理的资源(关闭文件、关闭游标等),您才需要使用 onStop.即便如此,我也会覆盖 DialogFragment 的 onStop 而不是底层 Dialog 的 onStop.

You only need to use onStop if you explicitly created any resources that require manual cleanup (closing files, closing cursors, etc.). Even then, I would override onStop of the DialogFragment rather than onStop of the underlying Dialog.

这篇关于如何正确关闭 DialogFragment?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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