How to keep map state on device rotation?

僤鯓⒐⒋嵵緔 提交于 2019-12-22 12:57:13

问题


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

It is something like this:

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


回答1:


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");



回答2:


You could use it like this because CameraPosition class implements Parcelable:

  1. save it
if (null != mMap) {
   outState.putParcelable("map_camera_position", mMap.getCameraPosition());
}
  1. retrieve it in onCreate()
if (null != savedInstanceState) {
    mCameraPosition = savedInstanceState.getParcelable("map_camera_position");
}
  1. set it to move the camera
if (null != mCameraPosition) {
   mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
}


来源:https://stackoverflow.com/questions/16257805/how-to-keep-map-state-on-device-rotation

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