Say I have a navigation graph similar to this:
--------- ---------
| Home | ---->| Other |
--------- ---------
|
|
V
---------
| Login |
---------
If the user isn't logged in, I've to show the login screen before he can proceed. As per the docs, I check whether the user is logged in or not in the HomeFragment
. If he isn't, I open the LoginFragment
. So far, so good.
But if the user presses back in the LoginFragment
, I want the app to exit. But since LoginFragment
isn't the start destination, it will simply open HomeFragment
which will open LoginFragment
again.
Currently, I quit the app by overriding onBackPressed()
in the host Activity
and finish()
the Activity
if the current destination is LoginFragment
.
But this feels hackish. I guess this must be a pretty common navigation scenario. So, is there any "idiomatic" way of doing this?
While some app developers use it to close their apps, some use it to traverse back to the app's previous activity. Many apps require the user to press the 'Back' button two times within an interval to successfully close the application, which is considered the best practice.
I believe the simplest (and I believe the appropriate) solution to your problem is to basically use app:popUpTo
and app:popUpToInclusive
in your action which takes from Home --> Login.
This is a relevant example where when you move from Splash to Home screen, you don't want use to go back to Splash screen when he presses "Back" button.
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