Android 导航组件导航到子图

Android Navigate Component navigate to sub graph

我有两个片段(OverviewFragment、PersonalFragment)和一个子图(包含两个片段:BucketsFragment和ObjectsFragment,BucketsFragment是开始目的地)。它们绑定到一个 BottomNavigateView。

现在,导航到子图开始目的地(BucketsFragment)后,继续导航到ObjectsFragment。然后导航到 OverviewFragment,最后 return 到子图。

现在,我开始destination(BucketsFragment),但实际上我想要的是ObjectsFragment。我该怎么办?

The whole process is shown here

我想导航到保留先前状态的子图,而不是新的子图。

根据 material design guidelines for bottom navigation:

On Android: the app navigates to a destination’s top-level screen. Any prior user interactions and temporary screen states are reset, such as scroll position, tab selection, and in-line search.

所以从技术上讲,这种行为是意料之中的。

当您在“资源”选项卡上并转到 ObjectsFragment 时,返回堆栈是

DashBoardFragment -> BucketsFragment -> ObjectsFragment

当您返回“概览”选项卡时,返回堆栈变为

DashBoardFragment

并且不会为不在返回堆栈上的片段保存任何状态。这就是为什么当您重新选择“资源”选项卡时,它会从头开始重新创建,然后您会返回到

DashBoardFragment -> BucketsFragment

有一个 existing issue for supporting multiple back stacks 旨在支持分别保存每个选项卡的状态,允许您希望的行为。根据该问题,这需要对 Fragments 的工作方式进行重大更改(因为它们是保存 Fragments 状态的方式)以及集成到 Navigation 本身。

该问题指出了一个临时解决方法,在 NavigationAdvancedSample where each tab uses its own separate navigation graph and separate NavHostFragment, thus allowing each one to keep its own state independently from one another. This requires a bit different of a setup in the MainActivity and the help of a set of NavigationExtensions 中进行了演示以使其正常工作。

一旦完成多个返回堆栈工作,预计所有这些功能都将合并到导航库本身中。