뒤로 탐색 기능은 사용자가 이전에 방문한 화면 기록을 통해 뒤로 이동하는 기능입니다. 모든 Android 기기는 이 유형의 탐색을 위해 뒤로 버튼을 제공하므로 앱 UI에 뒤로 버튼을 추가하지 마세요. 사용자의 Android 기기에 따라 이 버튼은 물리적 버튼 또는 소프트웨어 버튼이 될 수 있습니다.
Android는 사용자가 애플리케이션을 탐색할 때 대상의 백 스택을 유지합니다. 이를 통해 Android는 뒤로 버튼을 누를 때 이전 대상으로 적절하게 이동할 수 있습니다. 하지만, 최상의 사용자 환경을 제공하기 위해 앱에서 뒤로 이동하는 동작을 자체적으로 구현해야 하는 경우도 있습니다.
예를 들어, WebView를 사용할 때는 기본 뒤로 버튼 동작을 재정의하여 사용자에게 앱의 이전 화면 대신 웹 방문 기록을 통해 뒤로 이동하도록 하는 것이 좋습니다.
Android 13 이상에는 Android 기기용 뒤로 탐색 예측 동작이 포함되어 있습니다. 이 기능에 관한 자세한 내용은 뒤로 탐색 예측 동작 지원 추가를 참고하세요.
OnBackPressedDispatcher는 뒤로 버튼 이벤트가 하나 이상의 OnBackPressedCallback 객체로 전달되는 방법을 제어합니다. OnBackPressedCallback의 생성자는 초기 사용 설정 상태를 나타내는 불리언 값을 사용합니다. 콜백을 사용 설정하면, 즉 isEnabled()가 true을 반환하면 디스패처는 콜백의 handleOnBackPressed()를 호출하여 뒤로 버튼 이벤트를 처리합니다. 사용 설정 상태는 setEnabled()를 호출하여 변경할 수 있습니다.
콜백은 addCallback 메서드를 사용하여 추가됩니다. LifecycleOwner를 사용하는 addCallback() 메서드를 사용하는 것이 좋습니다.
이렇게 하면 LifecycleOwner가 Lifecycle.State.STARTED일 때만 OnBackPressedCallback이 추가되도록 할 수 있습니다.
또한 활동은 연결된 LifecycleOwner가 소멸될 때 등록된 콜백을 삭제합니다. 이는 메모리 누수를 방지하며, LifecycleOwner를 전체 기간이 활동보다 짧은 프래그먼트 또는 기타 수명 주기 소유자에 사용하기 적합하도록 만듭니다.
다음은 콜백 구현 예입니다.
Kotlin
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 순으로 호출됩니다.
콜백은 책임 연쇄(Chain of Responsibility) 패턴을 따릅니다. 체인의 각 콜백은 앞의 콜백이 사용 설정되지 않은 경우에만 호출됩니다. 즉, 앞의 예에서 콜백 two는 콜백 three가 사용 설정되지 않은 경우에만 호출되고 콜백 one은 콜백 two가 사용 설정되지 않은 경우에만 호출됩니다.
addCallback()을 사용하여 콜백이 추가되는 경우 LifecycleOwner가 Lifecycle.State.STARTED 상태로 전환될 때까지 책임 연쇄에 추가되지 않습니다.
임시 변경을 위해 OnBackPressedCallback의 사용 설정 상태를 변경하는 것이 좋습니다. 이렇게 하면 위에 설명한 순서가 유지됩니다.
이는 콜백이 중첩된 여러 수명 주기 소유자에 등록된 경우 특히 중요합니다.
OnBackPressedCallback을 완전히 삭제하려는 경우 remove()를 호출하면 됩니다.
콜백은 연결된 LifecycleOwner가 소멸될 때 자동으로 삭제되므로 일반적으로 필수사항은 아닙니다.
addCallback을 통해 등록된 모든 콜백은 super.onBackPressed()를 호출할 때 평가됩니다.
Android 12(API 수준 32) 이하에서는 OnBackPressedCallback의 등록된 인스턴스와 관계없이 onBackPressed가 항상 호출됩니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-27(UTC)
[[["이해하기 쉬움","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(UTC)"],[],[],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`."]]