Android Dev Summit, October 23-24: two days of technical content, directly from the Android team. Sign-up for livestream updates.

OnBackPressedCallback

abstract class OnBackPressedCallback
kotlin.Any
   ↳ androidx.activity.OnBackPressedCallback

Class for handling OnBackPressedDispatcher#onBackPressed() callbacks without strongly coupling that implementation to a subclass of ComponentActivity.

This class maintains its own enabled state. Only when this callback is enabled will it receive callbacks to handleOnBackPressed().

Note that the enabled state is an additional layer on top of the androidx.lifecycle.LifecycleOwner passed to OnBackPressedDispatcher#addCallback(LifecycleOwner, OnBackPressedCallback) which controls when the callback is added and removed to the dispatcher.

By calling remove(), this callback will be removed from any OnBackPressedDispatcher it has been added to. It is strongly recommended to instead disable this callback to handle temporary changes in state.

Summary

Public constructors

<init>(enabled: Boolean)

Create a OnBackPressedCallback.

Public methods

abstract Unit

Callback for handling the OnBackPressedDispatcher#onBackPressed() event.

Boolean

Checks whether this callback should be considered enabled.

Unit

Removes this callback from any OnBackPressedDispatcher it is currently added to.

Unit
setEnabled(enabled: Boolean)

Set the enabled state of the callback.

Public constructors

<init>

OnBackPressedCallback(enabled: Boolean)

Create a OnBackPressedCallback.

Parameters
enabled Boolean: The default enabled state for this callback.

Public methods

handleOnBackPressed

@MainThread abstract fun handleOnBackPressed(): Unit

Callback for handling the OnBackPressedDispatcher#onBackPressed() event.

isEnabled

@MainThread fun isEnabled(): Boolean

Checks whether this callback should be considered enabled. Only when this callback is enabled will it receive callbacks to handleOnBackPressed().

Return
Boolean: Whether this callback should be considered enabled.

remove

@MainThread fun remove(): Unit

Removes this callback from any OnBackPressedDispatcher it is currently added to.

setEnabled

@MainThread fun setEnabled(enabled: Boolean): Unit

Set the enabled state of the callback. Only when this callback is enabled will it receive callbacks to handleOnBackPressed().

Note that the enabled state is an additional layer on top of the androidx.lifecycle.LifecycleOwner passed to OnBackPressedDispatcher#addCallback(LifecycleOwner, OnBackPressedCallback) which controls when the callback is added and removed to the dispatcher.

Parameters
enabled Boolean: whether the callback should be considered enabled