使用导航库销毁片段/触发onDestroy的实例

时间:2020-01-19 00:00:15

标签: android android-fragments navigation android-jetpack

我正在使用导航库,我的用例是在按回时保留Fragment状态,这是通过在onViewCreated中返回已经膨胀的绑定来实现的,因为当更改片段时,导航似乎不会破坏该片段的现有实例,而实际的视图变量存在时您可以向后或向上导航。

但是当我需要重新创建此Fragment实例时,我也有一个用例,因此我希望有一种方法可以对该片段调用onDestroy()。但是我看不到任何用于删除/获取Backstack实例中现有的api。

所以我的问题是如何从nav的后堆栈中获取Fragment的现有实例并销毁它,或者只是通过调用nav controller api来删除它

一些代码:

 override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewModel = ViewModelProviders.of(requireActivity(), mViewModelFactory)
            .get(MainViewModel::class.java)
        parseNavigationExtra()
        return if (::mBinding.isInitialized) {
            mBinding.root
        } else {
        //create new binding
}

因此,当我调用此操作时,由于变量仍然存在,我仍然获得了旧的绑定根。

  <action
        android:id="@+id/clearBackStack"
        app:destination="@+id/mainFragment"
        app:launchSingleTop="true"
        app:popUpTo="@+id/mobile_navigation"
        app:popUpToInclusive="true" />

2 个答案:

答案 0 :(得分:0)

List<Fragment> fragments = getActivity().getSupportFragmentManager().getFragments();          
Fragment lastFragment = fragments.get(fragments.size() - 1);
getActivity().getSupportFragmentManager().beginTransaction().remove(emptyDialog);

答案 1 :(得分:0)

自2.1.0版以来

导航库中的更改

NavBackStackEntry:现在,您可以调用NavController.getBackStackEntry(),并在后向堆栈中传入目标或导航图的ID。返回的NavBackStackEntry除了提供用于启动该目的地的参数之外,还提供了导航驱动的LifecycleOwner,ViewModelStoreOwner(由NavController.getViewModelStoreOwner()返回的内容)和SavedStateRegistryOwner。

所以计划是使用新的api来查看NavBackStackEntry可用的内容。