Search code examples
androidxamarinfragment-tab-host

FragmentTabHost FragmentManager is invalid


I'm developing an app using xamarin.android in visual studio, and i'm trying to add Tabs on the buttom of my app
And this is my code

protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);                      

        SetContentView(Resource.Layout.Main);


        FragmentTabHost fragmentTabHost = (FragmentTabHost)FindViewById(Resource.Id.tabhost);
        fragmentTabHost.Setup(this, FragmentManager, Resource.Id.tabcontent);
    }

Then i get this error

cannot convert from 'Android.App.FragmentManager' to 'Android.Support.V4.App.FragmentManager'

And when i change this

fragmentTabHost.Setup(this, FragmentManager, Resource.Id.tabcontent);

To this

fragmentTabHost.Setup(this, Android.Support.V4.App.FragmentManager, Resource.Id.tabcontent);

I get this error instead

'FragmentManager' is a type, which is not valid in the given context

I've been stuck on this for a while, any help is appreciated

EDIT :
When i try to add a tab with this code

fragmentTabHost.AddTab(fragmentTabHost.NewTabSpec("fragmenta").SetIndicator("Fragment A"), new SubsFragment(), null);

I get this error

cannot convert fragment to java.Lang.class

Any advice is wellcome


Solution

  • Change

    fragmentTabHost.Setup(this, FragmentManager, Resource.Id.tabcontent);
    

    to

    fragmentTabHost.Setup(this, this.SupportingFragmentManager, Resource.Id.tabcontent);
    

    The compiler is expecting the support version of FragmentManager and you need to specify it as such. Just putting Android.Support.V4.App.FragmentManager doesn't work because that's a name of a class and it's expecting an instantiated object of type Android.Support.V4.App.FragmentManager.

    Another important thing, if you look at the code this.SupportingFragmentManager, you'll notice the keyword this being used. If you're calling this.SupportingFragmentManager from a FragmentActivity the code will work as is, otherwise get a reference to your FragmentActivity and call SupportingFragmentManager on it. Like so:

    fragmentTabHost.Setup(this, myFragmentActivity.SupportingFragmentManager, Resource.Id.tabcontent);

    Hope this helps.