Search code examples
android-fragmentsgoogle-maps-android-api-2supportmapfragment

SupportMapFragment with navigationDrawer


I have an activity that extends ActionBarActivity and has a navigation drawer. This is the xml layout of the activity:

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

And then I have a fragment with the map:

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

When I choose the Map section from the drawer the map fragment is attached to the container and I need to instanciate a GoogleMap object. I tried with:

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

and with

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

but always got NullPointerException.. I know it's not a problem of execution time because I even tried to instantiate the GoogleMap in a botton onClick() method that I pressed long after the map showed. How can I get my map reference?


Solution

  • Finally I managed to get it work with these 3 lines of code:

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