简体   繁体   中英

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 . However the solution only works on large devices where you put both fragments in the same 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.

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. It could instantiate the SharedViewModel and set the item passed as 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.

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? You can still have only one Activity holding the shared ViewModel between master and detail Fragment .

Then use Fragment transactions or NavigationController to switch between master and detail. 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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