使用jetpack导航调用Fragment两次

Rul*_*lan 5 navigation android android-fragments android-jetpack android-jetpack-navigation

我正在使用喷气背包导航,我需要通过活动传递一些参数。根据我的实际配置,当我调用 findNavController 时,该片段被调用两次。

这是正常的,因为我们正在以编程方式调用片段,并在 xml 中使用app:navGraph="@navigation/nav_graph"

我可以有一种方法来同时拥有两者并忽略 xml 吗?开发人员有时会犯错误并将其写在两个地方,并且没有人注意到该片段被调用了两次。

androidx.navigation:navigation-fragment-ktx:2.3.3
androidx.fragment:fragment-ktx:1.3.0
Run Code Online (Sandbox Code Playgroud)
findNavController(findViewById(R.id.nav_host_fragment))
    .setGraph(R.navigation.nav_graph, Bundle())
Run Code Online (Sandbox Code Playgroud)

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)