How to add a fragment to the backstack in MvvmCross 4.0?
Asked Answered
R

2

6

I have an Activity which hosts fragments in a frame-layout. If I change the displayed fragment to another, the fragment isn't added to the back-stack and therefore the use of the "Back"-button will immeditately close the app instead of navigating back (FragmentManager.BackStackEntryCount is always 0 in the OnBackPressed()-callback).

In the ViewModel of the "MainActivity" that hosts the fragments I show the fragment via the ShowViewModel<>-method:

public class MainViewModel : MvxViewModel
{
    public IMvxCommand ShowHomeCommand
    {
        get { return new MvxCommand(ShowHomeExecuted); }
    }

    private void ShowHomeExecuted()
    {
        ShowViewModel<HomeViewModel>();
    }
}

The fragment-class has an annotation to assign the ViewModel to a host-activity:

[MvxFragment(typeof(MainViewModel), Resource.Id.fragment_container)]
[Register("namespace.of.HomeFragment")]

I use the default AndroidViewPresenter in my Setup-class:

protected override IMvxAndroidViewPresenter CreateViewPresenter()
{
   var mvxFragmentsPresenter = new MvxFragmentsPresenter(AndroidViewAssemblies);
   Mvx.RegisterSingleton<IMvxAndroidViewPresenter>(mvxFragmentsPresenter);
   return mvxFragmentsPresenter;
}

I expected a parameter "AddToBackstack" or similar in the MvxFragment-Attribut or in the MvxFragment-class but there is nothing like this. Do I miss something or is there currently no support for the back-stack in the new fragment-mechanism in MvvmCross 4.0?

Raspy answered 20/3, 2016 at 13:13 Comment(0)
K
5

What you can do is add something like this to your MainActivity:

public override void OnBeforeFragmentChanging (IMvxCachedFragmentInfo fragmentInfo, Android.Support.V4.App.FragmentTransaction transaction)
        {
            var currentFrag = SupportFragmentManager.FindFragmentById (Resource.Id.content_frame) as MvxFragment;

            if(currentFrag != null 
                && fragmentInfo.ViewModelType != typeof(MenuViewModel) 
                && currentFrag.FindAssociatedViewModelType() != fragmentInfo.ViewModelType)
                fragmentInfo.AddToBackStack = true;
            base.OnBeforeFragmentChanging (fragmentInfo, transaction);
        }

This will add the fragment to the backstack before the navigation happens.

Kelseykelsi answered 21/3, 2016 at 9:59 Comment(0)
S
2

I think it is as simple as changing the attributes on your fragment to

[MvxFragment(typeof(MainViewModel), Resource.Id.fragment_container, AddToBackStack = true)]
[Register("namespace.of.HomeFragment")]

This certainly works in v4.2.3

Sartor answered 2/3, 2017 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.