如何在片段中使用FragmentManager - Xamarin
问题描述:
我在本网站上关注了本教程:http://www.c-sharpcorner.com/article/xamarin-android-create-google-map-with-marker/。它在MainActivity中100%工作,但只要我将代码移动到片段中,我就会收到一条错误消息,说'对象未设置为实例'。可能是什么问题呢 ?这里是我的代码:如何在片段中使用FragmentManager - Xamarin
public class ViewAlert : Fragment, IOnMapReadyCallback
{
View view = null;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.Inflate(Resource.Layout.ViewAlert, container, false);
try
{
SetUpMap();
}
catch (Exception ex)
{
}
return view;
}
private void SetUpMap()
{
if (GMap == null)
{
FragmentManager.FindFragmentById<MapFragment>(Resource.Id.googlemap).GetMapAsync(this);
}
}
public void OnMapReady(GoogleMap googleMap)
{
this.GMap = googleMap;
GMap.UiSettings.ZoomControlsEnabled = true;
LatLng latlng = new LatLng(Convert.ToDouble(gpsLatitude), Convert.ToDouble(gpsLongitude));
CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latlng, 15);
GMap.MoveCamera(camera);
MarkerOptions options = new MarkerOptions()
.SetPosition(latlng)
.SetTitle("Chennai");
GMap.AddMarker(options);
}
}
在这条线上出现的错误:
FragmentManager.FindFragmentById<MapFragment>(Resource.Id.googlemap).GetMapAsync(this);
我想:
view.FragmentManager.FindFragmentById<MapFragment>(Resource.Id.googlemap).GetMapAsync(this);
但没有奏效。
地图加载时没有标记。破坏代码负责将标记放置在地图上。
答
由于MapFragment
放在里面片段ViewAlert
,你必须使用ChildFragmentManager:
ChildFragmentManager.FindFragmentById<MapFragment>(Resource.Id.googlemap).GetMapAsync(this);
它的工作完全正常。谢谢 –