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

查看:178
本文介绍了如何不使用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时,都会重新创建该片段,目标片段中的所有网络任务都将重做,在androidX中切换时如何保持片段的状态?

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天全站免登陆