Saving MapFragment (Maps v2) State in Android

后端 未结 2 1331
北海茫月
北海茫月 2021-01-17 09:04

I\'m working with the new GoogleMaps API (v2) and have some problems with the fragment. I have two fragments in my app (Map, List) and the user can switch between them. Work

2条回答
  •  一整个雨季
    2021-01-17 09:42

    I solved this problem by holding on to a reference to the CameraPosition on the map in the onDestroyView() method of the fragment; then using that CameraPosition when reinstatiating the map.

    The context of my solution has it's own quirks, but essentially I have a map fragment nested within another fragment (which I'm hanging on to, even after it get's replaced). So this is the code in the parent fragment's onActivityCreated() method:

        GoogleMapOptions mapOptions = new GoogleMapOptions();
        if(_savedCameraPosition != null)
        {
            mapOptions.camera(_savedCameraPosition);
        }
        else
        {
            // Centre on Australia
            mapOptions.camera(CameraPosition.fromLatLngZoom(new LatLng(-24.25, 133.25), 15));
        }
        _mapFragment = new SupportMapFragment().newInstance(mapOptions);
    
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.map_holder, _mapFragment);
        fragmentTransaction.commit();
    

    Then later in the same class I have:

    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
        _savedCameraPosition = _map.getCameraPosition();
    }
    

提交回复
热议问题