Search code examples
androidandroid-fragmentsxamarinxamarin.androidmvvmcross

After updating MvvmCross 5.2 I have error Fragment already active


I have a problem after updating to the new MvvmCross 5.2.

I have forced uninstalled MvvmCross.Droid.Shared and after update all packages. I then got some errors with MvxFragment, so I replaced it with MvxFragmentPresentation. Additionally, I replaced MvxCachingFragmentCompatActivity with MvxAppCompatActivity and I'm now using the new MvxAppCompatViewPresenter. All works well, and the app running good. Except after I select logout in menu I'm taken to the LoginViewModel and when I want Login again I get this error

Fragment already active.

Can someone help me?

My test project is HERE on github.

It fail here, by the ShowViewModel

   public class MainViewModel : BaseViewModel
    {
        public void ShowMenu()
        {
            ShowViewModel<MenuViewModel>();
        }
    }

Solution

  • The issue is that you are mixing your methods for presenting in MvvmCross. With MvvmCross 5.x a new prefer way to navigate was introduced using the IMvxNavigationService. For new apps it is suggested that you rather make use of the IMvxNavigationService over the prior ShowViewModel. It is advised that you do not mix the use of the two different ways to navigate as you may get some strange behaviour.

    Switching to that IMvxNavigationService which you are already using on the LoginViewModel will solve the exception you are getting.

    protected readonly IMvxNavigationService _mvxNavigationService;
    
    public MainViewModel(IMvxNavigationService mvxNavigationService)
    {
        _mvxNavigationService = mvxNavigationService;
    }
    
    public void ShowMenu()
    {
        _mvxNavigationService.Navigate<MenuViewModel>();
    }
    

    Additionally, you will want to remove adding HomeFragment to the backstack to prevent seeing a white page when navigation back.

    [MvxFragmentPresentation(typeof(MainViewModel), Resource.Id.content_frame)]
    public class HomeFragment : BaseFragment<HomeViewModel>
    

    See pull request for full details of changes.


    Additional notes

    Rather than explicitly specifying MvxAppCompatViewPresenter in your Setup which inherits MvxAndroidSetup you can rather inherit from MvxAppCompatSetup which will automatically make use of the MvxAppCompatViewPresenter as well as register additional AndroidViewAssemblies relating to support libraries (see link to which assemblies) and FillTargetFactories for the MvxAppCompatSetupHelper.