当发生配置更改并因此重新创建我的 Activity 和 Fragment 时,我的导航 Graph 范围内的 ViewModel 不可用,而 Fragments 已经被再次创建。
似乎在 navGraph 之前重新创建了 Fragment。
我正在使用此代码从我的 Fragment 初始化我的 navGraph 范围 ViewModel:
private val myViewModel: MyViewModel by navGraphViewModels(R.id.nav_graph_id)
如果我尝试myViewModel
在 FragmentsonViewCreated
功能中使用,我会IllegalArgumentException
在配置更改后得到一个。例外:
java.lang.IllegalArgumentException: No destination with ID <destination id> is on the NavController's back stack
我该如何处理?
编辑1:
这是我的 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/main_nav_host"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:navGraph="@navigation/main_nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
这是我的 main_nav_graph.xml:
<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"
android:id="@+id/main_nav_graph"
app:startDestination="@id/main_nav_graph_1">
<navigation
android:id="@+id/main_nav_graph_1"
android:label="@string/nav_graph_1_label"
app:startDestination="@id/nav_graph_1_start_fragment">
<!-- nav graph stuff -->
</navigation>
<navigation
android:id="@+id/main_nav_graph_2"
android:label="@string/nav_graph_2_label"
app:startDestination="@id/nav_graph_2_start_fragment">
<fragment
android:id="@+id/nav_graph_2_start_fragment"
android:label="@string/nav_graph_2_start_fragment_label"
android:name="my.package.ui.NavGraph2StartFragment"
tools:layout="@layout/fragment_nav_graph_2_start">
</fragment>
<!-- In here is where I get the problem -->
</navigation>
</navigation>