在尝试创建 GoogleMap
对象(它返回 null)时,我在让 .getMap()
工作时遇到了很多麻烦,我环顾四周,发现人们也遇到了类似的问题,但无法从他们那里找到任何帮助。在当前的实现中,我如何找到 MapFragment
并从中创建 GoogleMap
?
protected void setFragment(){
FragmentManager fm = getFragmentManager();
MapFragment mapFragment = MapFragment.newInstance();
fm.beginTransaction().replace(R.id.fragment_container, mapFragment).commit();
try{
GoogleMap gMap = ((MapFragment)fm.findFragmentById(R.id.fragment_container)).getMap();
gMap.setBuildingsEnabled(true);
}catch(Exception e){ }
}
包含fragment_container的XML部分
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="@+id/selectionLayout">
<RelativeLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="85dp">
</RelativeLayout>
</RelativeLayout>
最佳答案
在开始使用之前允许加载Map
,否则您将得到null
。本地图可供使用时,您会收到 onReady
回调。
protected void setFragment(){
FragmentManager fm = getFragmentManager();
MapFragment mapFragment = MapFragment.newInstance();
fm.beginTransaction().replace(R.id.fragment_container, mapFragment).commit();
try{
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap map) {
//your map related actions.
}
});
}
catch(Exception e) {
e.printStackTrace();
}
}
关于java - MapFragment,GoogleMap .getMap(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31813278/