Java 在嵌套的mapfragment中调用getMap()会产生nullpointerexception
我在自定义片段中有一个mapfragment,就像在提供的答案中那样调用它 不幸的是,如果我调用getMap()-方法(请参阅附件代码),就会出现一个NullPointerException。有人知道为什么吗?谢谢你的帮助Java 在嵌套的mapfragment中调用getMap()会产生nullpointerexception,java,android,nullpointerexception,android-nested-fragment,mapfragment,Java,Android,Nullpointerexception,Android Nested Fragment,Mapfragment,我在自定义片段中有一个mapfragment,就像在提供的答案中那样调用它 不幸的是,如果我调用getMap()-方法(请参阅附件代码),就会出现一个NullPointerException。有人知道为什么吗?谢谢你的帮助 private void initializeMap() { initializeMapFragment(); try { // show current location map.setMyLocationEnabled(t
private void initializeMap() {
initializeMapFragment();
try {
// show current location
map.setMyLocationEnabled(true);
map.getUiSettings().setRotateGesturesEnabled(true);
map.getUiSettings().setZoomGesturesEnabled(true);
// adding marker
addDestinationMarker();
// zoom to current location
Location myLocation = map.getMyLocation();
if (myLocation != null) {
LatLng currentPosition = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder().target(currentPosition).zoom(12).build();
map.moveCamera(CameraUpdateFactory.newLatLng(currentPosition));
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void initializeMapFragment() {
MapFragment mapFragment = MapFragment.newInstance();
FragmentManager fm = getFragmentManager();
if (fm.findFragmentByTag("my_map_fragment") == null) {
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.map_container, mapFragment, "my_map_fragment").commit();
}
map = mapFragment.getMap();
}
编辑//
HomeFragment的xml如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:weightSum="1">
<FrameLayout
android:id="@+id/map_container"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1">
</FrameLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|bottom|left|right|center"
android:background="@drawable/bg_lines"
android:orientation="horizontal">
<Button
android:id="@+id/alarmButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/BlueButtonStyle"
android:text="@string/btn_alarm"/>
</LinearLayout>
发布片段的xml我已经将其添加到原始帖子中。我认为您需要等待
片段视图充气(和地图初始化),以便检索谷歌地图实例。因此,我建议您使用侦听器
在onViewCreated
之后调用。好吧,我不明白如何实现这一点。你能提供一些代码吗?谢谢!