7

Using Android's Navigation Component, I have 3 fragments hosted by a single Activity. The launch fragment is a splash screen fragment (A), if the user is not logged in, I launch the login fragment (B), if they are logged in, I launch a list fragment (C).

So launch routes are either A->B->C or A->C.

When you land on B or C, pressing back should kill the app. The NavigationController though is instead backs up to A (I think, A's onActivityCreated is certainly called at which point it crashes which is probably unrelated).

Pop behaviors in the graph editor for A -> B seem to allow me to pop to different fragments but there doesn't seem to be an option to just kill the app.

Do I really need to override onBackPressed for this behavior and just kill the activity? Because this is easier without the NavigationController, usually I would just finish an activity as I start a new one.

Daniel Wilson
  • 18,838
  • 12
  • 85
  • 135

1 Answers1

3

Open text tab in Graph Editor to view xml code, find your two actions A -> B and A -> C and put tag: app:clearTask="true", it's should kill you app when user press back button.

Example:

 <fragment
        android:id="@+id/launcher_fragment"
        android:name="com.example.LauncherFragment"
        android:label="launcher_fragment">
        <action
            android:id="@+id/action_launcher_to_login"
            app:destination="@id/login_fragment"
            app:clearTask="true"/>
        <action
            android:id="@+id/action_launcher_to_list"
            app:destination="@id/list_fragment"
            app:clearTask="true" />
    </fragment>
Bruno Milhan
  • 304
  • 2
  • 6
  • Oops. Nice one :) I think it really should be documented here: https://developer.android.com/topic/libraries/architecture/navigation/navigation-implementing – Daniel Wilson Sep 26 '18 at 07:52
  • 17
    This solution is no longer valid, because **app:clearTask="true"** is no longer available. See solution from this thread: https://stackoverflow.com/questions/53314555/navigation-architecture-how-to-manage-proper-navigation-without-using-cleartask – Dawid Tokarzewski Apr 05 '19 at 13:51
  • 1
    apparently you can use setPopupTo or popUpTo in xml to achieve that, you may read more from this post I found that meets your needs https://proandroiddev.com/android-navigation-component-tips-tricks-implementing-splash-screen-f0f5ce046a09 – Trung Le Jan 07 '20 at 16:06