SupportMapFragment with navigationDrawer

SupportMapFragment with navigationDrawer

我有一个 activity 扩展 ActionBarActivity 并有一个导航抽屉。这是 activity 的 xml 布局:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <fragment android:id="@+id/navigation_drawer"
              android:layout_width="@dimen/navigation_drawer_width"
              android:layout_height="match_parent"
              android:layout_gravity="start"
              android:name="mypackage.utils.NavigationDrawerFragment"
              tools:layout="@layout/fragment_navigation_drawer"/>

</android.support.v4.widget.DrawerLayout>

然后我有一个带有地图的片段:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity$PlaceholderFragment">

<fragment
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map"
    tools:context=".MainActivity"
    android:name="com.google.android.gms.maps.SupportMapFragment"/>

<ImageButton
    android:onClick="showUserPosition"
    android:background="@drawable/selector"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</RelativeLayout>

当我从抽屉中选择地图部分时,地图片段附加到容器,我需要实例化一个 GoogleMap 对象。我试过:

mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

并与

mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.container)).getMap();

但总是出现 NullPointerException。我知道这不是执行时间的问题,因为我什至尝试在地图显示很久之后按下的按钮 onClick() 方法中实例化 GoogleMap。我怎样才能得到我的地图参考?

最后我设法让它与这 3 行代码一起工作:

Fragment f = getSupportFragmentManager().findFragmentById(R.id.container);
SupportMapFragment mapFragment = (SupportMapFragment) f.getChildFragmentManager().findFragmentById(R.id.map);
GoogleMap mMap = mapFragment.getMap();