kotlinandroid-jetpack-composeandroid-jetpack-navigation

Jetpack Compose: close application by button


NavController can't pop programmatically the latest @Composable in the stack. I.e. popBackStack() doesn't work if it's a root page. So the application can be closed by tap on "Close" button view and only hardware Back key allows to leave application.

Example: Activity

class AppActivity : ComponentActivity() {
    override fun onCreate(state: Bundle?) {
        super.onCreate(state)
        setContent {
            val controller = rememberNavController()
            NavHost(controller, startDestination = HOME) {
                composable(HOME) { HomePage(controller) }
                ...
            }
        }
    }
}

HomePage.kt

@Composable
fun HomePage(controller: NavController) {
    Button(onClick = {
        controller.popBackStack()
    }) {
        Text("Exit")
    }
}

Question:

How to close the app in onClick handler if Compose Navigation is used.


Solution

  • You can use this:

    @Composable
    fun HomePage(controller: NavController) {
        val activity = (LocalContext.current as? Activity)
        Button(onClick = {
            activity?.finish()
        }) {
            Text("Exit")
        }
    }