简体   繁体   English

使用导航组件而不使用 ViewModel 时如何在后台堆栈中保留 Fragment 实例?

[英]How to preserve Fragment instance in backstack when using Navigation Component without using ViewModels?

Is there a way preserve my fragments instances so that they don't get recreates when coming back from another Fragment through navigation component?有没有办法保留我的片段实例,以便在通过导航组件从另一个片段返回时不会重新创建它们?

I thought of saving the fragment's instance in a variable and using it if it's not null in onCreateView(), but it seems this is not advised can generate memory leaks.我想过将片段的实例保存在一个变量中,如果它不是 onCreateView() 中的 null,则使用它,但似乎不建议这样做会产生 memory 泄漏。

It's my only option to refactor my app and use ViewModels in all my fragments?这是我重构应用程序并在所有片段中使用 ViewModel 的唯一选择吗?

When Fragment is recreated from back stack, first method which gets called is onCreateView while when Fragment is being created for first time, onAttach followed by onCreate is called.当从后台堆栈重新创建Fragment时,第一个调用的方法是onCreateView ,而当第一次创建Fragment时, onAttach后跟onCreate

So you can avoid reinitialization of variables using these one time invoked methods in order to preserve their previous states.因此,您可以避免使用这些一次性调用的方法重新初始化变量,以保留它们以前的状态。 But this is advisable for small use cases only.但这仅适用于小型用例。 To preserve larger data sets, you should consider using ViewModels which are bound to fragment lifecycle and retains the data until fragment is detached & destroyed.为了保留更大的数据集,您应该考虑使用绑定到片段生命周期并保留数据直到片段被分离和销毁的ViewModels

You can post your exact use case here if you need more help.如果您需要更多帮助,可以在此处发布您的确切用例。

暂无
暂无

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

相关问题 如果我使用 backstack 到达第六个片段,如何删除第一个片段? - How to remove the first fragment if I reached sixth fragment using backstack? 如何在导航抽屉中维护片段的后台堆栈? - How to maintain backstack of fragment in Navigation Drawer? 无法使用导航组件导航到所需的片段 - Unable to navigate to desired fragment using navigation component 当我们 go 使用 android 中的 backstack 回到上一个片段时,上一个片段正在重新启动 - Previous fragment is restarting when we go back to previous fragment using backstack in android 使用按钮和菜单项调用相同的片段(不在backStack中创建重复项) - Using a button and a menu item to call the same fragment (without creating duplicates in backStack) 使用视图模型将数据从活动发送到片段 - Send data to fragment from activity using viewmodels 有没有一种方法可以防止在使用Android导航组件时在bottomNavigation中重新创建片段 - Is there a way to prevent re-create fragment in bottomNavigation when using android navigation component 当点击从 WorkManager 发送的通知时,使用导航组件启动特定片段 - Launch a particular Fragment using Navigation component when tapped on Notification that is sent from WorkManager 如何使用片段保留活动之间的动态Arraylist元素(Android) - How to preserve dynamic Arraylist elements between activities using fragment (Android) 使用导航切换到另一个片段时保存片段数据 - Save Fragment data when switch to another fragment using Navigation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM