[英]How to get previous destination with navigation component?
I have fragments A, B, C, and X where their navigations are as the following.我有片段 A、B、C 和 X,它们的导航如下。
A --> X
B --> X
C --> X
How could I know the information of the last or previous destination in X?我怎么知道X中最后一个或上一个目的地的信息?
The current destination ID can be found by可以通过以下方式找到当前的目的地 ID
Navigation.findNavController(v).getCurrentDestination().getId()
I also tried using getBackStackEntry(int destinationId)
but it returns only the topmost NavBackStackEntry for a destination id.我也尝试使用
getBackStackEntry(int destinationId)
但它只返回目标 id 的最顶层 NavBackStackEntry。 In other words, the current destination.换句话说,当前目的地。
Also getActivity().getSupportFragmentManager().getBackStackEntryCount();
还有
getActivity().getSupportFragmentManager().getBackStackEntryCount();
returning 0.返回 0。
Possible solutions are:可能的解决方案是:
Is it possible to get the current destination?是否有可能获得当前目的地?
Java: Navigation.findNavController(v).getPreviousBackStackEntry().getDestination().getId();
Java:
Navigation.findNavController(v).getPreviousBackStackEntry().getDestination().getId();
Kotlin: findNavController().previousBackStackEntry?.destination?.id
Kotlin:
findNavController().previousBackStackEntry?.destination?.id
This should return you the previous destination's id in the 'X' fragment.这应该会在“X”片段中返回上一个目的地的 id。
add destination change listener.添加目标更改侦听器。 and compare id with A,B,C of ids on back key press
并在后退键按下时将 id 与 id 的 A、B、C 进行比较
NavController.OnDestinationChangedListener { controller, destination, arguments ->
// react on change or
//you can check destination.id or destination.label and act based on that
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.