Saving MapFragment (Maps v2) State in Android

你。 提交于 2019-12-01 15:02:14

How can I accomplish this?

If you replace() a fragment, the old fragment's views are destroyed, which takes out your MapView and, presumably, the CameraPosition.

onSaveInstanceState() is mostly for configuration changes, such as screen rotations. MapFragment and SupportMapFragment already retain the CameraPosition (which, BTW, is Parcelable, so you can save the whole object in the Bundle rather than piecemeal).

You could consider using show() and hide() instead of replace(), so the fragment and its views sticks around.

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!