classMyFragment:Fragment(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)// This callback will only be called when MyFragment is at least Started.valcallback=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 will only be called when MyFragment is at least Started.OnBackPressedCallbackcallback=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()}...}
您可以通过 addCallback() 提供多个回调。如果这样做,回调的调用顺序与其添加顺序相反,即最后添加的回调是第一个有机会处理返回按钮事件的回调。例如,如果您按顺序添加了三个名为 one、two 和 three 的回调,它们的调用顺序分别为 three、two 和 one。
回调遵循责任链模式。责任链中的每个回调仅在前面的回调处于未启用状态时调用。这意味着,在前面的示例中,仅当 three 回调处于未启用状态时,系统才会调用 two 回调。仅当 two 回调处于未启用状态时,系统才会调用 one 回调,以此类推。
[[["易于理解","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\nUsers navigate backward through screens using *back navigation* . Most Android\ndevices have a back button---physical, software, or gesture-based. Usually, you\nshouldn't add a back button to your app. However, Android Automotive OS (AAOS)\ndevices in compatibility mode use a system back button. This handles navigation,\nso you don't need to add your own. For details, see\n[AAOS Compatibility Mode](/training/cars/platforms/automotive-os/compatibility-mode).\n\nAndroid maintains a *back stack* of destinations as the user navigates\nthroughout your application. This usually allows Android to 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 in order to\nprovide the best possible user experience. For example, when using a `WebView`,\nyou might want to override the default Back button behavior to allow the user to\nnavigate back through their web browsing history instead of the previous screens\nin your app.\n| **Note:** Android 13 introduces predictive back navigation, which works with custom back navigation, for Android devices. We strongly recommend that you implement predictive back navigation as soon as possible. Otherwise, users might experience unexpected behavior in a future Android release. To learn more, see [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),\nallows you to 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. Only when a callback is enabled (i.e.,\n[`isEnabled()`](/reference/androidx/activity/OnBackPressedCallback#isEnabled())\nreturns `true`) will the dispatcher call 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 via the `addCallback` methods. It is strongly recommended to\nuse the [`addCallback()`](/reference/androidx/activity/OnBackPressedDispatcher#addCallback(androidx.lifecycle.LifecycleOwner,%20androidx.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 it suitable\nfor use in fragments or other lifecycle owners that have a shorter lifetime\nthan the activity.\n\nHere's 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 will only be 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 will only be 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 via [`addCallback()`](/reference/androidx/activity/OnBackPressedDispatcher#addCallback(%20androidx.activity.OnBackPressedCallback)).\nWhen doing so, the callbacks are invoked in the reverse order in which they are\nadded - the callback added last is the first given a chance to handle the\nBack button event. For example, if you added three callbacks named\n`one`, `two` and `three` in order, they would be invoked in the order of\n`three`, `two`, and `one`, respectively.\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` would be invoked only if callback `three`\nwas not enabled. Callback `one` would only be invoked if callback `two`\nwas not enabled, and so on.\n\nNote that when added via [`addCallback()`](/reference/androidx/activity/OnBackPressedDispatcher#addCallback(androidx.lifecycle.LifecycleOwner,%20androidx.activity.OnBackPressedCallback)),\nthe callback is not added to the chain of responsibility until the\n`LifecycleOwner` enters the\n[`Lifecycle.State.STARTED`](/reference/androidx/lifecycle/Lifecycle.State#STARTED)\nstate.\n\nChanging the enabled state on the `OnBackPressedCallback` is strongly\nrecommended for temporary changes as it maintains the ordering described above,\nwhich is particularly important if you have callbacks registered on multiple\ndifferent nested lifecycle owners.\n\nHowever, in cases where you want to remove the `OnBackPressedCallback` entirely,\nyou should call\n[`remove()`](/reference/androidx/activity/OnBackPressedCallback#remove()).\nThis is usually not necessary, however, because callbacks are automatically removed when their associated [`LifecycleOwner`](/reference/androidx/lifecycle/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 a\n[`OnBackPressedCallback`](/reference/androidx/activity/OnBackPressedCallback) instead.\nHowever, if you are unable to 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`."]]