导航组件可防止在按回时重新创建片段 [英] Navigation Component prevent to recreate fragment on back press

查看:167
本文介绍了导航组件可防止在按回时重新创建片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用Jetpack导航组件,但只有一个活动和一些片段.

I'm using the Jetpack Navigation Component in my project with a single activity and some fragments.

我有一个片段,其中包含一个从服务器端填充的列表.我在onViewCreated方法上调用getDataFromServer,然后,当用户单击某个项目时,将显示一个新片段.

I have a fragment with a list that fills from server side. I call getDataFromServer on the onViewCreated method then, when a user clicks on an item, a new fragment shows.

问题是,当我按下后退"按钮时,onViewCreated在列表片段中再次被调用.

The problem is that when I press the back button, onViewCreated is called again in my list fragment.

那么,如何防止再次创建我的第一个片段?我不要不必要的onViewCreated通话.

So, how can I prevent my first fragment from recreating again? I don't want unnecessary onViewCreated calls.

推荐答案

当然,我们不能阻止调用oncrateView,但是有一种简单的方法. 除了在onCreateView或其他生命周期方法中调用view.loadData()之外,我们还可以在初始化ViewModel时调用它.

Of course, we can not prevent calling oncrateView, but there is a simple way. Instead of calling view.loadData() in onCreateView or other lifecycle methods we can call it while initializing ViewModel

本文帮助我更好地了解了ViewModel 使用架构组件时的5个常见错误

this article helped me to know ViewModel better 5 common mistakes when using Architecture Components

更新:

当前导航组件(V 2.3.0)不支持此功能,它总是在导航到另一个片段时杀死该片段.假设您在Fragment A中有google map,那么每次返回到Fragment时,它都会再次初始化,并且相机移至用户位置!! (一个坏主意).

The current navigation component (V 2.3.0) doesn't support this feature, it always kills the fragment while navigating to another fragment. Imagine you have google map in Fragment A so each time you returns to the Fragment it initialized again and the camera moves to the user location!! (what a bad idea).

因此,最好的方法是在遇到相同问题时不要使用导航组件.

So the best way is not to use the navigation component if you have the same issue.

导航,保存片段状态,GitHub问题

这篇关于导航组件可防止在按回时重新创建片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆