BackHandler
Functions summary
Unit |
@ComposableAn effect for handling presses of the system back button. |
Functions
BackHandler
@Composable
fun BackHandler(enabled: Boolean = true, onBack: () -> Unit): Unit
An effect for handling presses of the system back button.
This effect registers a callback to be invoked when the system back button is pressed. The onBack will be invoked when the system back button is pressed (that is, onCompleted).
The handler is registered once and stays attached for the lifetime of the LifecycleOwner. Its OnBackPressedCallback.isEnabled state automatically follows the lifecycle: it becomes enabled when the lifecycle is at least Lifecycle.State.STARTED and disabled otherwise.
Precedence
If multiple BackHandler are present in the composition, the one that is composed last among all enabled handlers will be invoked.
Usage
It is important to call this composable unconditionally. Use the enabled parameter to control whether the handler is active. This is preferable to conditionally calling BackHandler (e.g., inside an if block), as conditional calls can change the order of composition, leading to unpredictable behavior where different handlers are invoked after recomposition.
Legacy Behavior
To restore the legacy add/remove behavior, set ActivityFlags.isOnBackPressedLifecycleOrderMaintained to false. In legacy mode, the handler is added on Lifecycle.Event.ON_START and removed on Lifecycle.Event.ON_STOP, which may change dispatch ordering across lifecycle transitions.
import androidx.activity.compose.BackHandler import androidx.compose.material.TextField import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember var text by remember { mutableStateOf("") } TextField(value = text, onValueChange = { text = it }) BackHandler(text.isNotEmpty()) { // handle back event }