在尝试创建.getMap()
对象(它返回null)时让GoogleMap
工作时遇到很多麻烦,我环顾四周,看到人们有类似的问题,但不是&#39能够从任何一个中找到任何帮助。在其当前实施中,我如何找到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>
答案 0 :(得分:2)
在开始使用之前允许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();
}
}
答案 1 :(得分:-2)
您实际上需要在布局中包含一个片段(而不是相对布局),如下所示:
<fragment
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />