MvvmCross: How to navigate from regular view to Mv

2019-06-02 08:28发布

问题:

I am slowly migrating my app over to MvvmCross on Android. I have not converted all Activities over to ViewModels yet. Therefore, I need to navigate from an Mvvm-controlled Activity to a regular Activity. To do this, I made my own Presenter and intercepted the Show method and did my own StartActivity. That seemed to work. However, now I need to go the other direction and have my regular Activity go back to the original Mvvm-controlled Activity. I tried just doing a StartActivity on the ViewModel using CLEAR_TOP flag, but I got an error:

"Null Extras seen on Intent when creating ViewModel - this should not happen - have you tried to navigate to an MvvmCross View directly?"

How can I go back to the original Mvvm-controlled activity from a regular Activity?

回答1:

Simple...

To go back from any standard Android Activity, you can simply ask the Activity to close using Finish()


But beyond that...

If instead you want to go forwards to an MvvmCross View, then you need to know a little about MvvmCross internals: in particular about how MvvmCross navigation conceptually happens between ViewModels rather than between Activities, Pages or UIViewControllers.

If you want to go forwards to a new ViewModel, then you can do this using the IMvxViewDispatcher singleton - how to do this is shown in Show view from non-view/viewmodel in mvvmcross

If you then later want to go back from the current ViewModel, then you can try calling Close(this) within the ViewModel - by default, on Android this will map to Finish(), on Touch to PopViewController, on WpDev to GoBack()



回答2:

This seemed to work, but is a hack since I use a special string "MvxLaunchData".

Intent i = new Intent(this,typeof(LoginView));
i.AddFlags(ActivityFlags.ClearTop);
var converter = Mvx.Resolve<IMvxNavigationSerializer> ();
MvxViewModelRequest request = MvxViewModelRequest.GetDefaultRequest (typeof(LoginViewModel));
i.PutExtra ("MvxLaunchData", converter.Serializer.SerializeObject(request));
StartActivity(i);

I will try the method shown in the other question you referenced.