I am planning to implement navigation like this:

The problem I face is when user is in
LoginFragmennt and presses back button it again loads up LognFragment ie. stuck in loop.
I navigate to LoginnFragment using conditional navigation as per this answer.
How to properly implement this?
One of the solutions that i can propose is to override inside your activity onBackPressed method, and finish the activity if your current destination(before on back pressed handled) is login fragment.
override fun onBackPressed() {
val currentDestination=NavHostFragment.findNavController(nav_host_fragment).currentDestination
when(currentDestination.id) {
R.id.loginFragment -> {
finish()
}
}
super.onBackPressed()
}
IMHO how I do it in my app is a little cleaner. Just add these settings in the nav graph:
<fragment
android:id="@+id/profile_dest"
android:name="com.example.ProfileFragment">
<action
android:id="@+id/action_profile_dest_to_login_dest"
app:destination="@id/login_dest"
app:popUpTo="@+id/profile_dest"
app:popUpToInclusive="true" />
</fragment>
and then navigate to login via
findNavController().navigate(R.id.action_profile_dest_to_login_dest).
popUpTo and popUpToInclusive close ProfileFragment when we navigate to LoginFragment so if the user navigates back, it exits the app.
来源:https://stackoverflow.com/questions/51582674/navigation-architecture-component-login-screen