Miha Markic
Miha Markic

Reputation: 3240

Fragments and ViewModels

I am trying to have a single activity with a dynamically created fragment within its view. I have a ActivityViewModel and a FragmentViewModel and matching views and layouts (ActivityView has a FrameLayout to host fragment). The fragment is shown by calling ShowViewModel<> from within ActivityViewModel.Start method. I am using a CustomePresenter as described in http://enginecore.blogspot.ro/2013/06/more-dynamic-android-fragments-with.html.

It works fine from cold start and after resume. However, it won't work after activity is destroyed.

This is the sequence that happens in this problematic situation: Activity is created, Mvx finds a cached ViewModel and attaches it to the Activity. Since ViewModel was cached it won't fire Start method (which triggers fragement creation). That's fine. But in next step Android recreates the fragment but it won't get its associated ViewModel because neither CustomPresenter (which takes care of that when fragment is created) or MvxFragment.OnCreate won't create it - like MvxActivity mechanism does. And thus I get a ViewModel-less fragment.

So I wonder, shouldn't be good if MvxFragemnt creates its own ViewModel upon create like MvxActivity does? Furthermore it should handle Save,Resume (call to adjacent ViewModel's methods). Or perhaps I am handling this in wrong way or missing something.

Upvotes: 2

Views: 1153

Answers (2)

WriteEatSleepRepeat
WriteEatSleepRepeat

Reputation: 3141

Sorry, you are correct. This behavior can be reproduced when creating a simple app with an activity and a fragment and then in the 'developer options' choose to always destroy activity. Now switch to another app and then switch back. Init and Start are not called, the activity view-model is obtained from the cached view model. This isn't related to fragments, it's about how view-model works for activity.

Now, regarding the fragment lifecycle and the fact that it doesn't get the view-model bound, as you mentioned, currently this is not available in Mvvmcross.

Upvotes: 1

Jelle
Jelle

Reputation: 385

I created a sample which describes the same problem, you are describing. You can alter the sample, to support multiple regions with multiple fragments in it. These regions can be used in presenter as well.

Please take a look at this presenter sample, which shows of a simple implementation of using fragments in an Android project: https://github.com/JelleDamen/CustomMvxAndroidPresenter

FYI: I used the same tutorial as an inspiration. Let me know if you need any help with it.

Upvotes: 1

Related Questions