【问题标题】:Android map in fragment nullpointer片段空指针中的Android地图
【发布时间】:2015-08-13 20:21:49
【问题描述】:

在我的项目中,我试图实现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>

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

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

地图的id = map (android:id="@+id/map")。

为什么是空指针?

【问题讨论】:

    标签: android google-maps android-fragments


    【解决方案1】:

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

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

    我建议你使用 getMapAsync 方法,因为 getMap 已被弃用

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

    【讨论】:

    • 使用 getChildFragmentManager() 后,我没有收到任何充气错误。非常感谢。
    【解决方案2】:

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

        View v =inflater.inflate(R.layout.fragment_map, container, false);
    
        map = v.findViewById(R.id.map))
                .getMap();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      • 2014-05-30
      • 2013-05-14
      相关资源
      最近更新 更多