[英]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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.