Search code examples
javaandroidandroid-fragmentsandroid-mapview

How to keep map state on device rotation?


I have a nested fragment that i would like to maintain the state when the device orientation changed.

It is something like this:

https://i.sstatic.net/FPE7q.png

I'm instantiate a mapView in the nested fragment and when the device is rotated the user must be in the same place where it was. How can I accomplish this?

Thank you


Solution

  • Ok, so i was making a mistake. I was calling the function setRetainInstance(true) on the fragment parent and i shouldn't.

    After deleting that line, it was very simple to keep the map state on device orientation. All i had to do was to save some values on onSaveInstanceState like this:

    bundle.putDouble("lat", mMap.getCameraPosition().target.latitude);
    bundle.putDouble("lon", mMap.getCameraPosition().target.longitude);
    bundle.putFloat("zoom", mMap.getCameraPosition().zoom);
    

    Then on onCreate, i restore the map state like this:

    bundle.getDouble("lat");
    bundle.getDouble("lon");
    bundle.getDouble("zoom");