Mvvmcross Android - Rotating fragment view during

2019-08-08 20:29发布

问题:

I'm having a problem when I try to manually re hydrate fragment viewmodels while rotating. Everything seems to work fine when I rotate a fragment once my viewmodel has been populated, all I do is :

this.viewmodel = foo

but if I try to rotate the fragment during population (e.g. from a web service) and then re-attach the stored viewmodel before population has completed the view doesn't appear to bind properly.

I know there is a lack of source (in this post) but I was wondering whether this should work in principle and if there was a way to fix the binding issue (a binding context etc does exist though) if that is indeed the issue?

if I rotate the fragment again after population the view populates as normal.

回答1:

I think I may have an initial solution to the problem I was having. I was using the following to run code post-.

TypedViewModel.PopulateAndRun(() =>
{
    DoSomething();
});

The problem seemed to be that this action was only called once and that possibly the action which was being fired was for the old view and not the new view.

I tried adding the following code in addition to the code above, and it worked

TypedViewModel.OnPopulated += () 
{
    DoSomething();
});


回答2:

One way to approach this problem is to instruct Android not to re-create the activity when configuration changes. Make sure you have "ConfigurationChanges" specificed in the activity attribute and you override OnConfigurationChanged.

    [Activity(
        Label = "Sample",
        ConfigurationChanges = global::Android.Content.PM.ConfigChanges.Orientation | global::Android.Content.PM.ConfigChanges.ScreenSize | global::Android.Content.PM.ConfigChanges.KeyboardHidden
        )]
    public class SampleActivity : MvxFragmentActivity
    {
        //...

        public override void OnConfigurationChanged(global::Android.Content.Res.Configuration newConfig)
        {
            base.OnConfigurationChanged(newConfig);
        }
    }