简体   繁体   English

Android 导航组件在弹出回栈时执行一个动作

[英]Android navigation component perform an Action when popping backstack

Im using the android navigation component and despite some early teething issues it is now working well.我使用的是 android 导航组件,尽管早期出现了一些问题,但它现在运行良好。

I'm keeping to the one activity many fragments design principle and I'm using shared view models to communicate between fragments.我坚持一个活动许多片段设计原则,我正在使用共享视图模型在片段之间进行通信。

I now have a scenario in my application where the user creates something, saves it, and is returned to the main list fragment (think something like adding a new contact except it involves a lot more than just typing in some boxes)我现在在我的应用程序中有一个场景,用户创建一些东西,保存它,然后返回到主列表片段(想像添加一个新的联系人,除了它涉及的不仅仅是在一些框中输入更多)

When the user saves the information I need to clear the data from my view models (this is due to security concerns and not performance) as they are shared view models and so are tied to the activity lifecycle and not the fragment, so they won't clear themselves, I can achieve this in a normal flow just setting data to null and calling navcontroller.popBackStack() but if the user presses back themselves I have no way of knowing and thus cannot clear these view models, any ideas?当用户保存信息时,我需要从我的视图模型中清除数据(这是出于安全考虑而不是性能),因为它们是共享视图模型,因此与活动生命周期而不是片段相关联,所以它们不会清除自己,我可以在正常流程中实现这一点,只需将数据设置为 null 并调用 navcontroller.popBackStack() 但是如果用户自己按下我无法知道因此无法清除这些视图模型,有什么想法吗?

You can implement a listener interface (say OnBackPressedListener) and use it in your respective fragments to take action upon back button presses (or up navigation).您可以实现一个侦听器接口(例如 OnBackPressedListener)并在您各自的片段中使用它以在按下后退按钮(或向上导航)时采取行动。 The interface will be your bridge between your fragments and the activity.该界面将成为您的片段和活动之间的桥梁。

The correct way to do this I don't think was available at the time but you should scope your view models to your navigation graphs, this way the data is cleared by the system and you only handle the navigation, quick example:执行此操作的正确方法我认为当时不可用,但您应该将视图模型的范围限定为导航图,这样系统会清除数据并且您只处理导航,快速示例:

private ViewModelStoreOwner getStoreOwner() {
        NavController navController = Navigation
                .findNavController(requireActivity(), R.id.root_navigator_fragment);
        return navController.getViewModelStoreOwner(R.id.root_navigator);        
}


private void setUpSearchViewModel() {
    searchViewModel = new ViewModelProvider(getStoreOwner()).get(SearchViewModel.class);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM