片段nullpointer中的Android地图

时间:2015-08-13 20:21:50

标签: android google-maps android-fragments

在我的项目中,我试图实现this solution来管理动态添加片段中的地图。

public class MapFragment extends Fragment {
    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    static final LatLng KIEL = new LatLng(53.551, 9.993);
    private GoogleMap map;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v =inflater.inflate(R.layout.fragment_map, container, false);

        map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();

        Marker kiel = map.addMarker(new MarkerOptions()
                .position(KIEL)
                .title("Kiel")
                .snippet("Kiel is cool")
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.ic_arrow)));

        // Move the camera instantly to hamburg with a zoom of 15.
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(KIEL, 15));
        // Zoom in, animating the camera.
        map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
        return v;
    }
}

我的观点:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/ColorBackground"
    tools:context="com.example.sven.questy.GameFragments.MapFragment">

    <fragment

         android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>

当我运行应用程序时,我得到一个nullpointer异常:

 map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();

map = map的id(android:id =&#34; @ + id / map&#34;)。

为什么是nullpointer?

2 个答案:

答案 0 :(得分:2)

由于您使用的是嵌套片段,因此应使用getChildFragmentManager()

SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);

我建议您使用getMapAsync方法,因为不推荐使用getMap

mapFragment.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(GoogleMap googleMap) {
        setupMap(googleMap);
    }
});

答案 1 :(得分:-1)

您需要在您获得的视图上使用See here,而不是使用片段管理器。地图附加到视图

    View v =inflater.inflate(R.layout.fragment_map, container, false);

    map = v.findViewById(R.id.map))
            .getMap();
相关问题