Android navigation component - change root fragment?

纵饮孤独 提交于 2021-02-05 06:48:21

问题


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:


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()
    )


来源:https://stackoverflow.com/questions/61031383/android-navigation-component-change-root-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!