简体   繁体   English

共享视图模型的主细节流程

[英]Master detail flow with shared viewmodel

This android documentation page in section "Share data between fragments" describes how to solve sharing of the selected item in the master detail flow using ViewModel . 这个Android文档页面的“片段之间共享数据”部分描述了如何使用ViewModel解决主详细信息流中所选项目的共享。 However the solution only works on large devices where you put both fragments in the same Activity . 但是,该解决方案仅适用于将两个片段都放在同一Activity中的大型设备。 On smaller devices the common approach is to have the detail fragment in its own DetailActivity and then the two fragments would have different ViewModel instances, so the approach would fail. 在较小的设备上,常用的方法是在其自己的DetailActivity包含细节片段,然后这两个片段将具有不同的ViewModel实例,因此该方法将失败。

So my question is how do you generalise this to all device sizes? 所以我的问题是,如何将其推广到所有设备尺寸?

I have one idea, I could put the two fragments in the same activity even on small devices. 我有一个主意,即使在小型设备上,我也可以将两个片段放在同一活动中。 Put this goes against every implementation of the master detail flow that I have ever seen. 将此与我见过的主细节流程的每个实现相违背。 It would be possible to implement the navigation fitting. 可以实现导航拟合。 And then the DetailActivity would only be used for displaying single items as an reaction to Intents. 然后, DetailActivity将仅用于显示单个项目以作为对Intent的反应。 It could instantiate the SharedViewModel and set the item passed as selectedItem . 它可以实例化SharedViewModel并将设置的项目设置为selectedItem Then the detail fragment can get an instance of the SharedViewModel the same way and doesn't need to differentiate between the two parent Activities. 然后,细节片段可以以相同的方式获取SharedViewModel的实例,而无需区分两个父活动。

This question is similar but people in the comments complained it is to broad and unclear 这个问题是相似的,但是人们在评论中抱怨这是广泛而不清楚的

why do you need a DetailActivity on smaller devices? 为什么在较小的设备上需要使用DetailActivity You can still have only one Activity holding the shared ViewModel between master and detail Fragment . 您仍然只有一个Activity可以在master和detail Fragment之间持有共享的ViewModel

Then use Fragment transactions or NavigationController to switch between master and detail. 然后使用Fragment事务或NavigationController在主要和详细信息之间切换。 The only difference is that both fragments won't be visible at the same time on screen but they will still share the underlying ViewModel linked to the parent Activity . 唯一的区别是两个片段将不会在屏幕上同时显示,但它们仍将共享链接到父Activity的基础ViewModel

Maybe at the time of asking the sunflower example was not available. 也许在问向日葵的例子时不可用。 Check it since it implements the master/detail flow for a list of plants, which seems to be what you are looking for. 对其进行检查,因为它实现了工厂列表的主/详细流程,这似乎正是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM