我有一个扩展ActionBarActivity的活动,并有一个导航抽屉。这是活动的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>当我从抽屉中选择Map部分时,映射片段被附加到容器上,我需要实例化一个GoogleMap对象。我试过:
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();并使用
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.container)).getMap();但总有NullPointerException..。我知道这不是执行时间的问题,因为我甚至试图在显示地图后很久才按下的botton onClick()方法中实例化onClick。我怎样才能得到我的地图参考?
发布于 2015-03-13 10:20:59
最后,我设法使它与以下3行代码一起工作:
Fragment f = getSupportFragmentManager().findFragmentById(R.id.container);
SupportMapFragment mapFragment = (SupportMapFragment) f.getChildFragmentManager().findFragmentById(R.id.map);
GoogleMap mMap = mapFragment.getMap();https://stackoverflow.com/questions/28991363
复制相似问题