classMyFragment:Fragment(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)// This callback is only called when MyFragment is at least startedvalcallback=requireActivity().onBackPressedDispatcher.addCallback(this){// Handle the back button event}// The callback can be enabled or disabled here or in the lambda}...}
Java
publicclassMyFragmentextendsFragment{@OverridepublicvoidonCreate(@NullableBundlesavedInstanceState){super.onCreate(savedInstanceState);// This callback is only called when MyFragment is at least startedOnBackPressedCallbackcallback=newOnBackPressedCallback(true/* enabled by default */){@OverridepublicvoidhandleOnBackPressed(){// Handle the back button event}};requireActivity().getOnBackPressedDispatcher().addCallback(this,callback);// The callback can be enabled or disabled here or in handleOnBackPressed()}...}
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-07-27。"],[],[],null,["# Provide custom back navigation\n\n*Back navigation* is how users move backward through the history of screens they\npreviously visited. All Android devices provide a Back button for this type of\nnavigation, so don't add a Back button to your app's UI. Depending on\nthe user's Android device, this button might be a physical button or a software\nbutton.\n\nAndroid maintains a *back stack* of destinations as the user navigates\nthroughout your application. This lets Android properly navigate to\nprevious destinations when the Back button is pressed. However, there are a few\ncases where your app might need to implement its own Back behavior to\nprovide the best possible user experience.\n\nFor example, when using a `WebView`,\nyou might want to override the default Back button behavior to let the user\nnavigate back through their web browsing history instead of the previous screens\nin your app.\n\nAndroid 13 and higher includes a predictive back gesture for Android devices. To\nlearn more about this feature, check out [Add support for the predictive back gesture](/guide/navigation/predictive-back-gesture).\n\nImplement custom back navigation\n--------------------------------\n\n[`ComponentActivity`](/reference/androidx/activity/ComponentActivity), the base\nclass for [`FragmentActivity`](/reference/androidx/fragment/app/FragmentActivity)\nand [`AppCompatActivity`](/reference/androidx/appcompat/app/AppCompatActivity),\nlets you control the behavior of the Back button by using its\n[`OnBackPressedDispatcher`](/reference/androidx/activity/OnBackPressedDispatcher),\nwhich you can retrieve by calling [`getOnBackPressedDispatcher()`](/reference/androidx/activity/ComponentActivity#getOnBackPressedDispatcher()).\n| **Note:** If your app uses Activity 1.5.0 or higher, you can also implement custom back navigation for a dialog by using [`ComponentDialog`](/reference/androidx/activity/ComponentDialog) and its `OnBackPressedDispatcher`.\n\nThe `OnBackPressedDispatcher` controls how Back button events are dispatched\nto one or more [`OnBackPressedCallback`](/reference/androidx/activity/OnBackPressedCallback)\nobjects. The constructor for `OnBackPressedCallback` takes a boolean for the\ninitial enabled state. When a callback is enabled---that is,\n[`isEnabled()`](/reference/androidx/activity/OnBackPressedCallback#isEnabled())\nreturns `true`---the dispatcher calls the callback's\n[`handleOnBackPressed()`](/reference/androidx/activity/OnBackPressedCallback#handleOnBackPressed())\nto handle the Back button event. You can change the enabled state by calling\n[`setEnabled()`](/reference/androidx/activity/OnBackPressedCallback#setEnabled(boolean)).\n\nCallbacks are added using the `addCallback` methods. We recommend using\nthe [`addCallback()`](/reference/androidx/activity/OnBackPressedDispatcher#addCallback(androidx.activity.OnBackPressedCallback))\nmethod, which takes a [`LifecycleOwner`](/reference/androidx/lifecycle/LifecycleOwner).\nThis ensures that the `OnBackPressedCallback` is only added when the `LifecycleOwner` is\n[`Lifecycle.State.STARTED`](/reference/androidx/lifecycle/Lifecycle.State#STARTED).\nThe activity also removes registered callbacks when their associated\n`LifecycleOwner` is destroyed, which prevents memory leaks and makes the\n`LifecycleOwner` suitable\nfor use in fragments or other lifecycle owners that have a shorter lifetime\nthan the activity.\n\nHere is an example callback implementation: \n\n### Kotlin\n\n```kotlin\nclass MyFragment : Fragment() {\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n\n // This callback is only called when MyFragment is at least started\n val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {\n // Handle the back button event\n }\n\n // The callback can be enabled or disabled here or in the lambda\n }\n ...\n}\n```\n\n### Java\n\n```java\npublic class MyFragment extends Fragment {\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n // This callback is only called when MyFragment is at least started\n OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {\n @Override\n public void handleOnBackPressed() {\n // Handle the back button event\n }\n };\n requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);\n\n // The callback can be enabled or disabled here or in handleOnBackPressed()\n }\n ...\n}\n```\n\nYou can provide multiple callbacks using `addCallback()`.\nWhen you do, the callbacks are invoked in the reverse order from the order you\nadd them---the callback added last is the first given a chance to handle the\nBack button event. For example, if you add three callbacks named\n`one`, `two`, and `three`, in that order, they are invoked in the order\n`three`, `two`, `one`.\n\nCallbacks follow the\n[Chain of Responsibility](https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern)\npattern. Each callback in the chain is invoked only if the preceding\ncallback was not enabled. This means that, in the\npreceding example, callback `two` is invoked only if callback `three`\nis not enabled, and callback `one` is only invoked if callback `two`\nis not enabled.\n\nNote that when the callback is added using `addCallback()`,\nit is not added to the chain of responsibility until the\n`LifecycleOwner` enters the `Lifecycle.State.STARTED` state.\n\nWe recommend changing the enabled state on the `OnBackPressedCallback`\nfor temporary changes, as doing so maintains the ordering described above.\nThis is particularly important if you have callbacks registered on multiple\nnested lifecycle owners.\n\nIn cases where you want to remove the `OnBackPressedCallback` entirely,\nyou can call\n[`remove()`](/reference/androidx/activity/OnBackPressedCallback#remove()).\nThis is usually not necessary, because callbacks are automatically removed when\ntheir associated `LifecycleOwner` is\n[destroyed](/reference/androidx/lifecycle/Lifecycle.State#DESTROYED).\n\nActivity onBackPressed()\n------------------------\n\nIf you are using\n[`onBackPressed()`](/reference/androidx/activity/ComponentActivity#onBackPressed())\nto handle Back button events, we recommend using an\n[`OnBackPressedCallback`](/reference/androidx/activity/OnBackPressedCallback) instead.\nHowever, if you can't make this change, the following rules apply:\n\n- All callbacks registered via `addCallback` are evaluated when you call `super.onBackPressed()`.\n- In Android 12 (API level 32) and lower, `onBackPressed` is always called, regardless of any registered instances of `OnBackPressedCallback`."]]