【发布时间】:2021-01-13 05:38:19
【问题描述】:
我相信有很多类似这个问题的问题。但是,我找不到解决问题的方法。问题是 popBackStack 函数从后台堆栈中删除了片段。但是,当另一个新导航发生时,它会崩溃。举个例子,我有三个片段,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。
提前致谢。
【问题讨论】:
-
你已经删除了你的第一个片段,然后你想导航到第一个片段怎么做?!
-
@AfshinSamiei 我在哪里删除了我的第一个片段?我刚刚将动作添加到第三个片段以显示它在哪里工作。但我想做同样的事情而不在第三个片段中声明那个动作。
-
popBackStack(R.id.firstFragment, true)弹出所有内容,包括第一个片段。你已经从后面的堆栈中弹出了每个片段。如果您只想返回第一个片段,似乎您想使用false,而不是true? -
@ianhanniballake 你太棒了。是的,该值为 false。
标签: android android-jetpack android-architecture-navigation