我想在片段中添加自定义布局的地图。
onCreateView
mapView = super.onCreateView(inflater, container, savedInstanceState);
扩展SupportMapFragment商店mapView,并将其插入到膨胀的布局中。主要问题是,然后片段尝试从保存状态恢复谷歌地图SDK内部粉碎。
还有其他方法可以解决这个问题。如果谷歌地图团队的某个人会推荐正确的方法会很好,因为你没有在样本中加入这样的东西。
答案 0 :(得分:13)
所有FragmentTransaction
都是异步的。如果您希望您的交易立即发生,您必须像以下一样强制执行:
getChildFragmentManager().beginTransaction.add(R.id.container, new MyMapFragment(), "MyMapFragment").commit();
getChildFragmentManager().executePendingTransactions();
/* getMap() should not return null here */
在使用
FragmentTransaction
提交FragmentTransaction.commit()
之后,计划在进程的主线程上异步执行它。如果要立即执行任何此类挂起操作,可以调用此函数(仅从主线程)来执行此操作。请注意,所有回调和其他相关行为都将在此调用中完成,因此请注意调用它的位置。<强>返回强>
如果有任何待执行的事务要执行,则返回true。
答案 1 :(得分:3)
您可以在片段(或活动)中使用MapView,这样您就可以使用您想要的任何布局。
即。您的布局可能如下所示:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
您还需要将Fragment的生命周期方法(如onCreate,onResume等)转发到MapView。
唯一的区别(似乎是Google地图中的错误?)是您还需要手动初始化Google地图:
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = mMapView.getMap();
if (mMap != null) {
// Thought official docs says that it is not necessary to call
// initialize() method if we got not-null GoogleMap instance from
// getMap() method it seems to be wrong in case of MapView class.
try {
MapsInitializer.initialize(getActivity());
setUpMap(mMap);
} catch (GooglePlayServicesNotAvailableException impossible) {
mMap = null;
}
}
}
}