Activity.FragmentManager is obsolete

Viewed 6130

I'm working on google maps using fragment. API version is 23.

mapFragment = FragmentManager.FindFragmentById<MapFragment>(Resource.Id.mapFragment);

The above code is highlighted that it's obsolete.

AXML file

<fragment 
        android:layout_width="match_parent"
        android:layout_height="200dp" 
        class="com.google.android.gms.maps.MapFragment"
        android:id="@+id/mapFragment"/>

Any idea on another way of implementing?

2 Answers

Well in simple terms Android recently marked all the old Fragment classes and its other supporting classes as obsolete.

Now it is adviced that you use the Support library Fragment, Fragment Manager.

How do you do that in Xamarin!

Inherit your fragment class from android.support.v4.app.Fragment instead of android.app.Fragment

Use SupportFragmentManager instead of FragmentManager which is well explained in this Java Guide

Change your AXML with:

<fragment 
    android:layout_width="match_parent"
    android:layout_height="200dp" 
    class="com.google.android.gms.maps.SupportMapFragment"
    android:id="@+id/mapFragment"/>

and your code with:

SupportMapFragment _mapFragment = (SupportMapFragment)SupportFragmentManager.FindFragmentByTag("mapFragment");
            if (_mapFragment == null)
            {
                GoogleMapOptions mapOptions = new GoogleMapOptions()
                    .InvokeRotateGesturesEnabled(true)
                    .InvokeScrollGesturesEnabled(true)
                    .InvokeCompassEnabled(true)
                    .InvokeAmbientEnabled(true)
                    .InvokeMapType(GoogleMap.MapTypeNormal)
                    .InvokeZoomControlsEnabled(true)
                    .InvokeCompassEnabled(true);

                _mapFragment = SupportMapFragment.NewInstance(mapOptions);

                Android.Support.V4.App.FragmentTransaction fragTx = SupportFragmentManager.BeginTransaction();
                fragTx.Add(Resource.Id.map, _mapFragment, "map");
                fragTx.Commit();

                _mapFragment.GetMapAsync(this);
Related