Android导航组件-更改根片段?

问题描述 投票:0回答:1

假设我有片段a-> b-> c,但是“ a”是启动屏幕,所以我希望“ b”成为堆栈中的第一个片段并永远抛出“ a”,所以当我是我时“ b”,然后按“返回”系统按钮-我关闭了该应用]

在SupportFragmentManager中,我使用了replace()并成功了。但是如何在这里实现呢?

android android-navigation android-navigation-graph
1个回答
0
投票

这里是一个例子

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>

并且在SplashFragment中,您只需要导航到OnCreate()中的家庭

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

同样,如果您只想在代码中执行此操作

findNavController()
    .navigate(R.id.action_splashFragment_to_homeFragment,
            null,
            NavOptions.Builder()
                    .setPopUpTo(R.id.splashFragment,
                            true).build()
    )
© www.soinside.com 2019 - 2024. All rights reserved.