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()}...}
您可以透過 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"]],["上次更新時間: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`."]]