我在自定义片段中有一个mapfragment,通过调用它来提供here
不幸的是,如果我调用了getMap() - Method(参见附件代码),那么会出现NullPointerException。有谁知道为什么?谢谢你的帮助!
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>