Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit app on back press in a non start destination?

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?

like image 801
AnEnigmaticBug Avatar asked Feb 09 '19 15:02

AnEnigmaticBug


People also ask

How do I close an app on back press?

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.


1 Answers

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.

enter image description here

like image 194
Wahib Ul Haq Avatar answered Nov 01 '22 19:11

Wahib Ul Haq