androidkotlinnavigationandroid-jetpackfragment-backstack

Navigation PopUpToInclusive doenst work? When the app is reopened, it opens the Login Fragment instead of Email Login Fragment


I'm using android jetpack navigation and the flow of the app is: Login screen → Email Login screen

nav_main.xml

<fragment android:id="@+id/loginFragment"
          android:name="com.example.myapp.ui.main.LoginFragment"
          android:label="@string/login"
          tools:layout="@layout/fragment_login" >

    <action
        android:id="@+id/action_login_to_emailLoginFragment"
        app:destination="@id/emailLoginFragment"
        app:popEnterAnim="@anim/slide_in_right"
        app:popExitAnim="@anim/slide_out_right"
        app:popUpTo="@+id/loginFragment"
        app:popUpToInclusive="true"/>

</fragment>

<fragment android:id="@+id/emailLoginFragment"
          android:name="com.example.myapp.ui.main.EmailLoginFragment"
          android:label="EmailLoginFragment"
          tools:layout="@layout/fragment_login_email" />

LoginFragment.kt

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    binding.emailLoginButton.setOnClickListener {
        findNavController().navigate(R.id.action_login_to_emailLoginFragment)
    }

    return binding.root
}

So, I open the app on the login fragment, I click the button, I go to email login fragment, when I click on the back button I return to the device's home screen. But the problem is when I open the app again, it opens in login fragment instead of email login fragment.


Solution

  • It sounds like you have the wrong definition of what popuptoIncusive does.

    popUpToInclusive="true" to indicate that the destination specified in app:popUpTo should also be removed from the back stack.
    

    If you are closing the app when you go to the home screen the expected behavior would be for the navigation component to launch the Host fragment, in your case the login in fragment.

    If you send the app to the background when you go to the home screen, and bring the app to the foreground you will still be in the email fragment.