What's the proper way to implement Fragments in MvvmCross 4.1.4
Asked Answered
D

1

6

I am looking for an example or documentation to work with fragments in the current mvvmcross version. I found a lot of information about the old versions but I am confused how I should implement it now.

The best information so far I have found is in this article: http://gregshackles.com/presenters-in-mvvmcross-navigating-android-with-fragments/

But it is over one year old and I think there is already a newer/better way to do it.

What I want is having a single Activity(like in an SPA or having a MainView) this activity should contain one or two fragment and on a button click I want to navigate/change to a different fragment and the current one on the backstack for navigation. Or is it recommend to use only activities for navigation and not implementing a SPA?

Thanks for your help! Timo

Dihedron answered 19/5, 2016 at 9:32 Comment(0)
C
15

The new way to use fragments in MvvmCross is by using attributes on your fragment.

[MvxFragment(typeof(ActivityHostViewModel), Resource.Id.content_frame, true)]
public class HomeFragment : BaseFragment<HomeViewModel>
{
}

The MvvmCross presenter will recognize that this is a fragment, and show it inside the host activity which is attached to the host viewmodel.

To support fragments in the presenter you need to add the following to your setup.cs

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

A full sample is available here: https://github.com/MvvmCross/MvvmCross/tree/develop/TestProjects/Android-Support/Fragments

Cherise answered 19/5, 2016 at 10:2 Comment(6)
Thank you for your fast answer, I have seen this example already but was not sure, if this is currently the proper way to do it. I will take a deeper look into it. :)Dihedron
Let me know if you have any questions about it.Cherise
Hi Martijn00, I have used the sample that you provided on your github. It is quite useful and handy. I am stuck with the following #37334369Halliehallman
I have asked a new question about this topic at this place: #37434204Dihedron
Hi Martijn00, the sample link returns 404, would it be possible to update the link? Thanks!Portecochere
I downloaded the sample code and understand how it works - when ShowViewModel(myViewModelType) is called, it will inject the respective view into the content_frame. But what happens when this is done on iOS? Won't it push a new UIViewController onto the stack?Newberry

© 2022 - 2024 — McMap. All rights reserved.