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?
Android Jetpack's Navigation component helps you implement navigation, from simple button clicks to more complex patterns, such as app bars and the navigation drawer. The Navigation component also ensures a consistent and predictable user experience by adhering to an established set of principles.
The NavHostFragment for dynamic features. A host is a single context or container for navigation via a NavController . It is strongly recommended to construct the nav controller by instantiating a NavHostController , which offers additional APIs specifically for a NavHost.
To retrieve the NavController for a fragment, activity, or view, use one of the following methods: Kotlin: Fragment. findNavController()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With