使用导航组件从 Backstack 中移除片段

Remove Fragments from Backstack using Navigation Component

我相信有很多类似这个问题的问题。但是,我找不到解决我遇到的问题的方法。问题是 popBackStack 函数从 backstack 中删除了片段。但是,当发生另一个新导航时它会崩溃。我举个例子,我有三个片段,FragmentFirst、FragmentSecond 和 FragmentThird。一张导航图,

<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/nav_a"
    app:startDestination="@id/firstFragment">

    <fragment
        android:id="@+id/firstFragment"
        android:name="com.example.myapplication.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first" >
        <action
            android:id="@+id/action_firstFragment_to_secondFragment"
            app:destination="@id/secondFragment" />
    </fragment>
    <fragment
        android:id="@+id/secondFragment"
        android:name="com.example.myapplication.SecondFragment"
        android:label="SecondFragment" >
        <action
            android:id="@+id/action_secondFragment_to_thirdFragment"
            app:destination="@id/thirdFragment" />
    </fragment>
    <fragment
        android:id="@+id/thirdFragment"
        android:name="com.example.myapplication.ThirdFragment"
        android:label="ThirdFragment" >
    </fragment>
</navigation>

第一个片段,

button.setOnClickListener {
    findNavController().navigate(R.id.action_firstFragment_to_secondFragment)
}

第二个片段,

button2.setOnClickListener {
    view.findNavController().navigate(R.id.action_secondFragment_to_thirdFragment)
}

第三个片段,

button3.setOnClickListener {
    findNavController().popBackStack(R.id.firstFragment, true)
}

现在,我可以从第一导航到第二,从第二导航到第三,从第三导航到第一。但是当我再次按下 First 中的按钮时,它崩溃了,消息是

id/action_firstFragment_to_secondFragment cannot be found from the current destination NavGraph

如果我在图表中创建一个动作,

<fragment
    android:id="@+id/thirdFragment"
    android:name="com.example.myapplication.ThirdFragment"
    android:label="ThirdFragment" >
    <action
        app:popUpTo="@id/firstFragment"
        app:popUpToInclusive="true"
        android:id="@+id/action_thirdFragment_to_firstFragment"
        app:destination="@id/firstFragment" />
</fragment>

而在第三个片段中,

button3.setOnClickListener {
    findNavController().navigate(R.id.action_thirdFragment_to_firstFragment)
}

在这种情况下,它工作得很好。但是,由于我正在使用的应用程序的限制,我想使用 popBackStack。

提前致谢。

popBackStack(R.id.firstFragment, true) 弹出所有内容,包括第一个片段。您已将所有片段从后台堆栈中弹出。似乎您想使用 false,而不是 true,如果您只想 return 到第一个片段。