【问题标题】:Android navigation component - change root fragment?Android导航组件 - 更改根片段?
【发布时间】:2020-04-05 17:10:03
【问题描述】:

假设我有片段 a->b->c ,但是“a”是一个启动画面,所以我希望“b”成为堆栈中的第一个片段并永远抛出“a”,所以当我是 i “b”并按“返回”系统按钮 - 我关闭应用程序

在 SupportFragmentManager 中,我使用了 replace() 并且有效。但是我怎样才能在这里实现呢?

【问题讨论】:

    标签: android android-navigation android-navigation-graph


    【解决方案1】:

    这是一个例子

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

    【讨论】:

    • 我在启动片段中有 app:popUpToInclusive="true" 并且应用程序仍然返回到它
    • 您是否尝试将导航库更新到最新版本
    • 重要,没有 app:popUpTo="@id/splashFragment" 不起作用
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多