How to add snippet to backstack in MvvmCross 4.0?

I have an Activity in which fragments are placed in the layout. If I change the displayed fragment to another, the fragment will not be added to the rear stack, and therefore using the back button will immediately close the application instead of navigating back (FragmentManager.BackStackEntryCount is always 0 in OnBackPressed () -callback).

In the ViewModel "MainActivity" in which the fragments are placed, I display the fragment using 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 for assigning ViewModel 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 was expecting the "AddToBackstack" parameter or similar in the MvxFragment-Attribut or in the MvxFragment class, but there was nothing like that. Am I missing something or not back-stack support in the new fragmentator in MvvmCross 4.0?

+5
source share
2 answers

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 stack before starting navigation.

+5
source

I think it's as simple as changing the attributes of your fragment to

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

It certainly works in v4.2.3

0
source

Source: https://habr.com/ru/post/1245419/


All Articles