2

J'ai une activité qui étend ActionBarActivity et possède un tiroir de navigation. Ceci est la mise en page XML de l'activité:SupportMapFragment avec navigationDrawer

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

Et puis j'ai un fragment avec la carte:

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

Quand je choisis la section Carte du tiroir le fragment de carte est fixé au récipient et j'ai besoin d'instancier un objet GoogleMap. J'ai essayé avec:

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

et

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

mais toujours eu NullPointerException .. Je sais que ce n'est pas un problème de temps d'exécution parce que j'ai même essayé d'instancier le GoogleMap dans une botton méthode onClick() que j'ai appuyé longtemps après la carte a montré. Comment puis-je obtenir ma référence de carte?

Répondre

1

Enfin, je réussi à le faire fonctionner avec ces 3 lignes de code:

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

GetMap est dépréciée –

+1

Merci, utilisé getMapAsync (OnMapReadyCallback rappel) à la place. –