Search code examples
androidandroid-activitystateandroid-mapviewmapactivity

How can I center my MapView on initial load only?


I'm working on an Android application with a MapActivity and I'm having trouble managing the MapView state in an appropriate manner.

Basically I have an activity that starts the MapActivity when it exits and at this point I need to center the map. All other times that the MapActivity is viewed I need it to basically retain it's last state and not change its position or zoom level or anything. It works fine when navigating to other activities as long as the MapActivity is not destroyed completely however I need the map to retain it's state when the device orientation changes. As most Android developers know the Activity is destroyed and re-created when that happens, at which point my MapView re-centers and I don't want it to.

How can I arrange my code so that I can execute my centering routine when the MapActivity is started from my other activity, and not execute my centering routine otherwise?


Solution

  • Return something non-null from onRetainNonConfigurationInstance(). Then, wherever you are centering the map, call getLastNonConfigurationInstance(). If it's null, center; if it is non-null, don't center.