使用导航组件将视图模型范围划分为多个片段(非活动) [英] Scoping a viewmodel to multiple fragments (not activity) using the navigation component

本文介绍了使用导航组件将视图模型范围划分为多个片段(非活动)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用导航组件,我希望在几个片段之间共享一个视图模型,但是当我离开片段时,应该将它们清除(因此不能将它们限定在活动范围内)活动很多碎片的方法。我已经设法使用多个导航主机并使用getParentFragment对片段进行作用域限定,但这只会导致更多问题,必须将片段包装在其他父片段中,使后退按钮无缝工作,其他黑客无法正常工作非常简单。有谁对如何实现这一目标有个好主意?我想知道getViewModelStore是否可以使用,鉴于下面的图像,我想将视图模型的作用域限定为createCardFragment2,并在其后的任何内容(addPredictions,editImageFragment和我尚未添加的其他内容)中使用它,但是如果我导航回到mainFragment,我想清除视图模型。

I'm using the navigation component, I want a view model to be shared between a few fragments but they should be cleared when I leave the fragments (hence not scoping them to the activity) I'm trying to take the one activity many fragments approach. I have managed to achieve this using multiple nav hosts and scoping the fragments to it using getParentFragment but this just leads to more issues having to wrap fragments in other parent fragments, losing the back button working seamlessly and other hacks to get something to work that should be quite simple. Does anyone have a good idea on how to achieve this? I wondered if theres anything with getViewModelStore I could be using, given the image below I want to scope a view model to createCardFragment2 and use it in anything after it (addPredictions, editImageFragment, and others i haven't added yet), but then if I navigate back to mainFragment I want to clear the view models.

顺便说一句,我不能只在mainFragment视图模型存储上调用clear,因为这里还有其他不应清除的视图模型,我想我想要一种告诉导航的方法托管我知道的父片段应该是什么,或者如果我要从mainFragment或cardPreviewFragment导航,则不是一种使视图模型新的方式

BTW I cant just call clear on mainFragment view model store as there are other view models here that shouldn't be cleared, I guess i want a way to tell the nav host what the parent fragment should be which I'm aware isn't going to be a thing, or a way to make the view model new if I'm navigating from mainFragment or cardPreviewFragment

推荐答案

是的,现在可以将viewmodel的范围限定为navgraph从 androidx.navigation:*:2.1.0-alpha02 开始。请参见此处的发行说明以及该API的示例此处。您需要提供的是导航图的 R.id 。但是,我发现使用它有点烦人,因为通常在 onCreate 中初始化了视图模型,在此范围内这是不可能的,因为不能保证nav控制器是

Yes, it's possible to scope a viewmodel to a navgraph now starting with androidx.navigation:*:2.1.0-alpha02. See the release notes here and an example of the API here. All you need to give is the R.id for your navgraph. I find it a bit annoying to use, though, because normally viewmodels are initialized in onCreate, which isn't possible with this scope because the nav controller isn't guaranteed to be set by your nav host fragment yet (I'm finding this is the case with configuration changes).

此外,如果您不希望 mainFragment 作为该范围的一部分,我建议将其删除,并可能使用嵌套导航图

Also, if you don't want your mainFragment to be part of that scope, I would suggest taking it out and maybe using a nested nav graph.

这篇关于使用导航组件将视图模型范围划分为多个片段(非活动)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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