Sam
Sam

Reputation: 6395

Disable back button in Jetpack Compose

How can I disable the back button in Jetpack Compose? I don't want the user to go back to previous screen.

I tried below code but the user can still go back to the previous screen:

BackHandler(enabled = false) {
   // do nothing
}

Upvotes: 21

Views: 12443

Answers (2)

RadekJ
RadekJ

Reputation: 3043

The other answer disables back navigation by consuming all back navigation events. If you still want to handle back in another composables then you can use this approach:

@Composable
fun DisableBackHandler(
    isDisabled: Boolean,
    content: @Composable () -> Unit,
) {
    CompositionLocalProvider(
        values = LocalOnBackPressedDispatcherOwner.current?.let { parentDispatcherOwner ->
            arrayOf(
                LocalOnBackPressedDispatcherOwner provides if (isDisabled) {
                    DummyOnBackPressedDispatcherOwner(parentDispatcherOwner.lifecycle)
                } else {
                    parentDispatcherOwner
                },
            )
        } ?: arrayOf(),
        content = content,
    )
}

private class DummyOnBackPressedDispatcherOwner(
    override val lifecycle: Lifecycle,
) : OnBackPressedDispatcherOwner {
    override val onBackPressedDispatcher: OnBackPressedDispatcher
        get() = OnBackPressedDispatcher()
}

It disables back handling for only part of your composition.

Upvotes: 0

Raj
Raj

Reputation: 1595

You should set enabled to true for taking control of back button. Then call BackHandler from the current destination in your NavHost

NavHost(
    navController = navController,
    startDestination = startDestination
) {

    composable(
        route = "Your Destination Route"
    ) {

        BackHandler(true) {
            // Or do nothing
            Log.i("LOG_TAG", "Clicked back")
        }

        YourDestinationScreen()
    }
}

Upvotes: 44

Related Questions