Jetpack Compose + AndroidViewBinding backpress will close the app

596 Views Asked by At

I have a navhostfragment inside an AndroidViewBinding in a Composable function. However, when I press the back button on the phone, the app closes. How can I avoid this and just go up in the backstack.

@Composable
fun MyComposeScreen() {
    AndroidViewBinding(FragmentLoginBinding::inflate)
}

FragmentLoginBinding

<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"

        app:defaultNavHost="true"
        app:navGraph="@navigation/login_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>
1

There are 1 best solutions below

0
On

You can use the BackHandler Composable provided by the androidx.activity.compose library:

implementation "androidx.activity:activity-compose:1.4.0"

Then, modify your MyComposeScreen

@Composable
fun MyComposeScreen() {
    val navController = rememberNavController()
    val backDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
    AndroidViewBinding(FragmentLoginBinding::inflate) {
        val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val inflater = navHostFragment.navController.navInflater
        val graph = inflater.inflate(R.navigation.login_navigation)
        navController.graph = graph
        navController.setBackStackEntryCount(1)

        BackHandler(backDispatcher) {
            navController.navigateUp()
        }
    }
}