从 Fragment 内创建 DialogFragment 时,请使用 fragment 的子 FragmentManager,以便在配置更改后状态可以正确恢复。非 null 标记让您可以使用 findFragmentByTag() 稍后检索 DialogFragment。
Kotlin
// From another Fragment or Activity where you wish to show this
// PurchaseConfirmationDialogFragment.
PurchaseConfirmationDialogFragment().show(
childFragmentManager, PurchaseConfirmationDialog.TAG)
Java
// From another Fragment or Activity where you wish to show this
// PurchaseConfirmationDialogFragment.
new PurchaseConfirmationDialogFragment().show(
getChildFragmentManager(), PurchaseConfirmationDialog.TAG);
[null,null,["最后更新时间 (UTC):2023-09-26。"],[],[],null,["# Display dialogs with DialogFragment\n\nA [`DialogFragment`](/reference/androidx/fragment/app/DialogFragment) is a\nspecial fragment subclass that is designed for creating and hosting\n[dialogs](/guide/topics/ui/dialogs). Although you don't need to\nhost your dialog within a fragment, doing so lets the\n[`FragmentManager`](/guide/fragments/fragmentmanager) manage the state\nof the dialog and automatically restore the dialog when a configuration\nchange occurs.\n| **Note:** This guide assumes familiarity with creating dialogs. For more information, see the [guide to dialogs](/guide/topics/ui/dialogs).\n\nCreate a DialogFragment\n-----------------------\n\nTo create a `DialogFragment`, create a class that extends\n[`DialogFragment`](/reference/androidx/fragment/app/DialogFragment) and\noverride\n[`onCreateDialog()`](/reference/androidx/fragment/app/DialogFragment#onCreateDialog(android.os.Bundle)),\nas shown in the following example. \n\n### Kotlin\n\n```kotlin\nclass PurchaseConfirmationDialogFragment : DialogFragment() {\n override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =\n AlertDialog.Builder(requireContext())\n .setMessage(getString(R.string.order_confirmation))\n .setPositiveButton(getString(R.string.ok)) { _,_ -\u003e }\n .create()\n\n companion object {\n const val TAG = \"PurchaseConfirmationDialog\"\n }\n}\n```\n\n### Java\n\n```java\npublic class PurchaseConfirmationDialogFragment extends DialogFragment {\n @NonNull\n @Override\n public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {\n return new AlertDialog.Builder(requireContext())\n .setMessage(getString(R.string.order_confirmation))\n .setPositiveButton(getString(R.string.ok), (dialog, which) -\u003e {} )\n .create();\n }\n\n public static String TAG = \"PurchaseConfirmationDialog\";\n}\n```\n\nSimilar to how\n[`onCreateView()`](/reference/androidx/fragment/app/Fragment#onCreateView(android.view.LayoutInflater,%20android.view.ViewGroup,%20android.os.Bundle))\ncreates a root `View` in an ordinary fragment, `onCreateDialog()`\ncreates a [`Dialog`](/reference/android/app/Dialog) to display\nas part of the `DialogFragment`. The `DialogFragment` handles displaying\nthe `Dialog` at appropriate states in the fragment's lifecycle.\n| **Note:** `DialogFragment` owns the [`Dialog.setOnCancelListener()`](/reference/android/app/Dialog#setOnCancelListener(android.content.DialogInterface.OnCancelListener)) and [`Dialog.setOnDismissListener()`](/reference/android/app/Dialog#setOnDismissListener(android.content.DialogInterface.OnDismissListener)) callbacks. You must not set them yourself. To find out about these events, override [`onCancel()`](/reference/android/content/DialogInterface.OnCancelListener#onCancel(android.content.DialogInterface)) and [`onDismiss()`](/reference/android/content/DialogInterface.OnDismissListener#onDismiss(android.content.DialogInterface)).\n\nAs with `onCreateView()`, you can return any subclass of `Dialog`\nfrom `onCreateDialog()` and aren't limited to using\n[`AlertDialog`](/reference/androidx/appcompat/app/AlertDialog).\n\nShow the DialogFragment\n-----------------------\n\nYou don't have to manually create a `FragmentTransaction` to\ndisplay your `DialogFragment`. Instead, use the `show()` method to\ndisplay your dialog. You can pass a reference to a `FragmentManager`\nand a `String` to use as a `FragmentTransaction` tag.\n\nWhen creating\na `DialogFragment` from within a `Fragment`, use the fragment's\nchild `FragmentManager` so that the state properly restores\nafter configuration changes. A non-null tag lets you use\n`findFragmentByTag()` to retrieve the `DialogFragment` at a later time. \n\n### Kotlin\n\n```kotlin\n// From another Fragment or Activity where you wish to show this\n// PurchaseConfirmationDialogFragment.\nPurchaseConfirmationDialogFragment().show(\n childFragmentManager, PurchaseConfirmationDialog.TAG)\n```\n\n### Java\n\n```java\n// From another Fragment or Activity where you wish to show this\n// PurchaseConfirmationDialogFragment.\nnew PurchaseConfirmationDialogFragment().show(\n getChildFragmentManager(), PurchaseConfirmationDialog.TAG);\n```\n\nFor more control over the\n[`FragmentTransaction`](/reference/androidx/fragment/app/FragmentTransaction),\nyou can use the\n[`show()`](/reference/androidx/fragment/app/DialogFragment#show(androidx.fragment.app.FragmentManager,%20java.lang.String))\noverload that accepts an existing `FragmentTransaction`.\n| **Note:** Because the `DialogFragment` automatically restores after configuration changes, consider only calling `show()` based on user actions or when `findFragmentByTag()` returns `null`, indicating that the dialog is not already present.\n\nDialogFragment lifecycle\n------------------------\n\nA `DialogFragment` follows the standard fragment lifecycle,\nwith a few additional lifecycle callbacks. The most\ncommon ones are as follows:\n\n- [`onCreateDialog()`](/reference/androidx/fragment/app/DialogFragment#onCreateDialog(android.os.Bundle)): override this callback to provide a `Dialog` for the fragment to manage and display.\n- [`onDismiss()`](/reference/androidx/fragment/app/DialogFragment#onDismiss(android.content.DialogInterface)): override this callback if you need to perform any custom logic when your `Dialog` is dismissed, such as releasing resources or unsubscribing from observable resources.\n- [`onCancel()`](/reference/androidx/fragment/app/DialogFragment#onCancel(android.content.DialogInterface)): override this callback if you need to perform any custom logic when your `Dialog` is canceled.\n\n`DialogFragment` also contains methods to dismiss or set the cancelability\nof your `DialogFragment`:\n\n- [`dismiss()`](/reference/androidx/fragment/app/DialogFragment#dismiss()): 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 are popped. Otherwise, a new transaction is committed to remove the fragment.\n- [`setCancelable()`](/reference/androidx/fragment/app/DialogFragment#setCancelable(boolean)): control whether the shown `Dialog` is cancelable. Use this method instead of directly calling [`Dialog.setCancelable(boolean)`](/reference/android/app/Dialog#setCancelable(boolean)).\n\nYou don't override\n[`onCreateView()`](/reference/androidx/fragment/app/Fragment#oncreateview)\nor\n[`onViewCreated()`](/reference/androidx/fragment/app/Fragment#onViewCreated(android.view.View,%20android.os.Bundle))\nwhen using a `DialogFragment` with a `Dialog`. Dialogs aren't only\nviews---they have their own window. As such, it's not enough to override\n`onCreateView()`. Moreover, `onViewCreated()` is never called on a\ncustom `DialogFragment` unless you've overridden `onCreateView()` and\nprovided a non-null view.\n| **Note:** When subscribing to lifecycle-aware components such as `LiveData`, never use [`viewLifecycleOwner`](/reference/androidx/fragment/app/Fragment#getviewlifecycleowner) as the [LifecycleOwner](/reference/androidx/lifecycle/LifecycleOwner) in a `DialogFragment` that uses `Dialog` objects. Instead, use the `DialogFragment` itself, or, if you're using [Jetpack Navigation](/guide/navigation), use the [`NavBackStackEntry`](/reference/androidx/navigation/NavBackStackEntry).\n\nUse custom views\n----------------\n\nYou can create a `DialogFragment` and display a dialog by overriding\n[`onCreateView()`](/reference/androidx/fragment/app/Fragment#onCreateView(android.view.LayoutInflater,%20android.view.ViewGroup,%20android.os.Bundle)).\nYou can either give it a `layoutId`, as with a typical fragment, or use the\n[`DialogFragment` constructor](/reference/androidx/fragment/app/DialogFragment#DialogFragment(int)).\n\nThe `View` returned by `onCreateView()`\nis automatically added to the dialog. In most cases, this means that you\ndon't need to override\n[`onCreateDialog()`](/reference/androidx/fragment/app/DialogFragment#onCreateDialog(android.os.Bundle)),\nas the default empty dialog is populated with your view.\n\nCertain subclasses of `DialogFragment`, such as\n[`BottomSheetDialogFragment`](/reference/com/google/android/material/bottomsheet/BottomSheetDialogFragment),\nembed your view in a dialog that is styled as a bottom sheet."]]