如何不使用 androidX 销毁片段 [英] how not to destroy fragment with androidX

查看:20
本文介绍了如何不使用 androidX 销毁片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我尝试使用 androidX 的导航和底部导航栏,当我像下面这样使用它时<代码>supportFragmentManager = getSupportFragmentManager();navHostFragment =(NavHostFragment)supportFragmentManager.findFragmentById(R.id.frag_nav);navController = navHostFragment.getNavController();NavigationUI.setupWithNavController(navigation, navController);

now ,I try androidX's navigation and bottom-navigationbar,when I use it like below supportFragmentManager = getSupportFragmentManager(); navHostFragment =(NavHostFragment)supportFragmentManager.findFragmentById(R.id.frag_nav); navController = navHostFragment.getNavController(); NavigationUI.setupWithNavController(navigation, navController);

发现一个问题,每次切换bottomNavigationBar,fragment都会重新创建,目标fragment中的所有网络任务都会重做,androidX切换时如何保持fragment的状态?

I found an issue,everytime switch the bottomNavigationBar,the fragment will be recreate,all network task in target fragment will be redo,how to keep fragment's state when it switch in androidX?

推荐答案

我也遇到了同样的问题.我将 BottomNavigationView 与导航架构组件一起使用,并且每次都重新创建片段.这是您在 Google 问题跟踪器中看到的预期行为 (https://issuetracker.google.com/issues/109856764).

I also had the same issue. I'm using BottomNavigationView with navigation architecture components and every time fragment is recreated. This is intended behaviour as you can see in Google issue tracker (https://issuetracker.google.com/issues/109856764).

因此,解决此问题的正确方法是将当前视图状态保存在 ViewModel 中,并在每个新创建的片段中观察该状态.您需要在 ViewModel 中完成所有网络任务.

So the right way to approach this is to save current view state in ViewModel and observe that state in every newly created fragment. You need to do all your network tasks in ViewModel.

还要注意在片段中获取 ViewModel 的方式.如果你这样做 viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java),ViewModel 将获得片段范围(片段被销毁时它会被销毁).您必须获得具有活动范围的 ViewModel,以便它可以在片段之间的切换中幸存下来.你可以这样做 viewModel = ViewModelProviders.of(activity!!, viewModelFactory).get(MyViewModel::class.java)

Also take care of the way you fetch ViewModel inside fragment. If you do it like this viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java), ViewModel will get fragment scope(it will be destroyed when fragment gets destroyed). You have to get ViewModel with activity scope so it can survive switch between fragments. You can do it like this viewModel = ViewModelProviders.of(activity!!, viewModelFactory).get(MyViewModel::class.java)

这篇关于如何不使用 androidX 销毁片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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