MapFragment,GoogleMap .getMap()

MapFragment, GoogleMap .getMap()

我在尝试创建 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){  }

}

XML 的部分包含 fragment_container

<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>

您实际上需要像这样在您的布局中包含一个片段(不是相对布局):

<fragment
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />

在您开始使用之前允许 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();
    }
}