[英]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.