Search code examples
androidgoogle-mapsxamarinmvvmcross

AndroidGms.Maps.MapFragment to Android.Views.View


I am trying to add a map on the MvxFragment, but getting the following error

There is no implicit reference conversion from 'AndroidGms.Maps.MapFragment' to 'Android.Views.View'

xml

<fragment
   android:id="@+id/map"
   android:layout_width ="match_parent"
   android:layout_height ="match_parent"
   android:name="com.google.android.gms.maps.MapFragment"/>

View.cs

public class MapView : MvxFragment<MapViewModel>, IOnMapReadyCallback
{
    private GoogleMap mMap;
    private View view;

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

        var ignored = base.OnCreateView(inflater, container, savedInstanceState);
        view = this.BindingInflate(Resource.Layout.MapView, null);
        SetUpMap();
        return view;
     }

     private void SetUpMap()
     {
       if (mMap == null)
        {
         // the error appears here
         view.FindViewById<MapFragment>(Resource.Id.map).GetMapAsync(this);
        }
      }
 }

enter image description here


Update :

If I either use FragmentManager or ChildFragmentManager, then I am getting the following error

enter image description here


Solution

  • A Fragment is not a View, hence you cannot use the FindViewById method. What then, how do you find your Fragment then?

    You need to use the FragmentManager or ChildFragmentManager (I will let you figure out which one to use in what case).

    Then you can call FindFragmentById to get your Fragment on a FragmentManager:

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

    Now you should be able to call GetMapAsync on your MapFragment to get the GoogleMap.

    EDIT:

    Seems like ChildFragmentManager doesn't have the generic version of FindFragmentById, you can do this instead:

    var mapFragment = ChildFragmentManager.FindFragmentById(Resource.Id.map).JavaCast<MapFragment>();