Android navigation component - change root fragment?

Viewed 2012

let's say I have fragments a->b->c , but "a" is a splash screen, so I want "b" to become first fragment in stack and throw "a" forever, so when I'm i "b" and press "back" system button - I close the app

In SupportFragmentManager I used replace() and that worked. But how can I achieve it here?

1 Answers

here is an example

graph.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
app:startDestination="@id/splashFragment">

<fragment
    android:id="@+id/splashFragment"
    android:name="com.example.***.fragments.SplashFragment"
    android:label="SplashFragment"
    tools:layout="@layout/layout_splash">
    <action
        android:id="@+id/action_splashFragment_to_homeFragment"
        app:destination="@id/homeFragment"
        app:popUpTo="@id/splashFragment"
        app:popUpToInclusive="true"/> // here to make home fragment as root
</fragment>
<fragment
    android:id="@+id/homeFragment"
    android:name="com.example.***.fragments.HomeFragment"
    android:label="HomeFragment"
    tools:layout="@layout/layout_home">
</fragment>
</navigation>

and in SplashFragment you just need to navigate to Home in OnCreate()

findNavController().navigate(R.id.action_splashFragment_to_homeFragment)

also if you want to do this in code only

findNavController()
    .navigate(R.id.action_splashFragment_to_homeFragment,
            null,
            NavOptions.Builder()
                    .setPopUpTo(R.id.splashFragment,
                            true).build()
    )
Related