DialogFragment 相对于 AlertDialog 的优势 [英] DialogFragment advantages over AlertDialog
问题描述
在开发 Android 应用程序时,我读到建议使用 DialogFragment
而不是直接使用 AlertDialog
来显示警报和确认.
When developing an Android app, I've read that it's recommended to use DialogFragment
instead of using directly an AlertDialog
to show alerts and confirmations.
这是在 DialogFragment 的文档中完成的:http://developer.android.com/reference/android/app/DialogFragment.html
This is done, for example, on DialogFragment's Documentation: http://developer.android.com/reference/android/app/DialogFragment.html
人们也说他们更喜欢这里:Android DialogFragment vs Dialog
People also say they prefer this here: Android DialogFragment vs Dialog
我想知道这种方法的优点,因为代码变得更加复杂.
I would like to know the advantages of this approach, since the code becomes more complex.
谢谢
推荐答案
在 Dialog 上使用 DialogFragment:
<小时>自从引入 API 级别 13:
showDialog
方法已弃用.不建议在代码中的其他地方调用对话框,因为您必须自己管理对话框(例如方向更改).不使用showDialog会导致偶尔的异常,对话框没有链接到任何Activity. the showDialog method from Activity is deprecated. Invoking a dialog elsewhere in code is not advisable since you will have to manage the dialog yourself (e.g. orientation change). Not using the showDialog will result in occasional exceptions, the dialog is not linked to any Activity.
关于showDialog的注意事项:
Note about showDialog:
Dialog 的参考:活动提供了一种工具来管理对话框的创建、保存和恢复.请参见 onCreateDialog(int)、onPrepareDialog(int, Dialog)、showDialog(int) 和dismissDialog(int).如果使用这些方法,getOwnerActivity() 将返回管理此对话框的 Activity.
reference of Dialog: Activities provide a facility to manage the creation, saving and restoring of dialogs. See onCreateDialog(int), onPrepareDialog(int, Dialog), showDialog(int), and dismissDialog(int). If these methods are used, getOwnerActivity() will return the Activity that managed this dialog.
DialogFragment 和 AlertDialog 的区别
阅读您的问题时会想到一件事.他们有那么大的不同吗?DialogFragment 与 Dialog 非常相似,只是包裹在一个片段中.来自关于 DialogFragment 的 Android 参考:
One thing that comes to mind when reading your question. Are they so much different? A DialogFragment is pretty similar to a Dialog, it's just wrapped inside a fragment. From Android reference regarding DialogFragment:
DialogFragment 是一个显示对话框窗口的片段,浮动在其顶部活动窗口.该片段包含一个 Dialog 对象,它根据片段的状态适当显示.控制对话框(决定何时显示、隐藏、关闭)应该完成通过 API 此处,而不是直接调用对话框.>
A DialogFragment is a fragment that displays a dialog window, floating on top of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. 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.
其他注意事项
- 由于具有不同屏幕尺寸的设备的多样性,Fragment 是 Android 框架中的一种自然演变.
- DialogFragments 和 Fragments 在支持库中可用,这使得该类可用于所有当前使用的 Android 版本.
这篇关于DialogFragment 相对于 AlertDialog 的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!