【发布时间】:2014-08-25 10:51:26
【问题描述】:
我正在使用以下代码在 Xamarin.Android 中显示地图:
private SupportMapFragment mapFragment;
private GoogleMap map;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
mapFragment = SupportFragmentManager.FindFragmentByTag ("map") as SupportMapFragment;
if (mapFragment == null) {
GoogleMapOptions options = new GoogleMapOptions ()
.InvokeCompassEnabled (true)
.InvokeMapType (GoogleMap.MapTypeNone)
.InvokeZoomControlsEnabled (false);
FragmentTransaction frx = SupportFragmentManager.BeginTransaction ();
mapFragment = SupportMapFragment.NewInstance (options);
frx.Add (Resource.Id.map,mapFragment,"map");
frx.Commit ();
}
if (map == null)
map = mapFragment.Map;
CircleOptions circle = new CircleOptions ();
circle.InvokeCenter (new LatLng(18.5203,73.8567));
circle.InvokeRadius (1000);
map.AddCircle (circle);
我的 AXML 是
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
在设备上成功部署后,map.AddCircle (circle); 线上出现异常,因为System.NullReferenceException 已被抛出Object Reference is not set to an instance of an Object。
我做错了什么?有什么需要初始化的吗?
【问题讨论】:
-
您确定您使用的布局正确吗?
-
是的,我使用了正确的布局
-
@user3249477:之前它对我有用。但现在相同的代码给了我例外。
-
您在 map.AddCircle(circle) 遇到的异常意味着 map == null。在之前的代码中,您正在检查地图上的空值,如果它为空,则执行 map = mapFragment.Map。你不检查那是否不为空。所以很可能 map 和 mapFragment.Map 都是空的。因此这段代码给你这个错误。
标签: android google-maps xamarin fragment