[英]Prevent destroying (or restore state) of Fragment B when navigating back from D - Navigation Component
I have fragments: A, B, C, D. I navigate A -> B .我有片段: A, B, C, D. 我导航 A -> B 。 Fragment B gets and saves state from arguments.
片段 B 从参数中获取并保存状态。 Then I navigate B -> C. And then C -> D. When I call two times
findNavController().popBackStack()
I get correct behavior: D -> B and B still has correct state.然后我导航 B -> C。然后 C -> D。当我调用两次
findNavController().popBackStack()
我得到了正确的行为:D -> B 和 B 仍然具有正确的状态。 It works because fragment B has never been destroyed, just its view.它有效是因为片段 B 从未被销毁,只是它的视图。 And then view is recreated when coming back.
然后返回时重新创建视图。 But calling two times popBackStack() isn't recommended action.
但是不推荐调用两次 popBackStack() 。 We should instead use the action with
app:popUpTo
and app:popUpToInclusive="true"
:我们应该改为使用
app:popUpTo
和app:popUpToInclusive="true"
:
<action
android:id="@+id/action_fragmentD_to_fragmentB"
app:destination="@id/fragmentB"
app:popUpTo="@+id/fragmentB"
app:popUpToInclusive="true" />
But it forces fragment B to be destroyed completely and then recreated.但它迫使片段 B 完全销毁,然后重新创建。 Bu with no previous state .
没有以前的状态。
In other words I want to achieve the same behavior as with Activities when used FLAG_ACTIVITY_CLEAR_TOP + FLAG_ACTIVITY_SINGLE_TOP
: https://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP换句话说,我想在使用
FLAG_ACTIVITY_CLEAR_TOP + FLAG_ACTIVITY_SINGLE_TOP
时实现与活动相同的行为: https : //developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP
There's no requirement to have an app:destination="@id/fragmentB"
on an action if you don't want to navigate to a new instance of fragmentB
(since that's what app:destination
does).如果您不想导航到
fragmentB
的新实例,则不需要在操作上使用app:destination="@id/fragmentB"
(因为app:destination
这样做的)。 Therefore you can use:因此,您可以使用:
<action
android:id="@+id/action_fragmentD_to_fragmentB"
app:popUpTo="@+id/fragmentB" />
This is identical to calling popBackStack(R.id.fragmentB, false)
- ie, pop back to fragmentB
, but don't pop fragmentB
itself.这与调用
popBackStack(R.id.fragmentB, false)
- 即弹出回到fragmentB
,但不弹出fragmentB
本身。
You can use the class SingleLiveEvent to retain the previous state since it emits the data only once whenever required.您可以使用类SingleLiveEvent来保留以前的状态,因为它在需要时仅发出一次数据。
learn more about SingleLiveEvent:了解有关 SingleLiveEvent 的更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.