0

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>
Sukitha Udugamasooriya
  • 2,268
  • 1
  • 35
  • 56
  • 1
    you need to implement the back press handling yourself in the activity hosting the composable. The OnBackPressedDispatcher should be used to override the default back press behavior when the navigation component has screens in its back stack. – Saurabh Jun 30 '23 at 09:43

1 Answers1

0

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()
        }
    }
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31