I'm using a fragment (v4) inside an activity. The fragment shows a GoogleMap and I I would like to save the camera position/state of the map when the app goes into the background and restore the camera once it comes to foreground again.
android.support.v4.app.Fragment
The camera state is saved in onSaveInstanceState(Bundle) and restored in onViewStateRestored(Bundle). But I wonder if those methods are the correct one. Why? Because onSaveInstanceState is called when you switch to another activity in the same app but also when you go back to the home screen or if you start another app. Everything's fine. But the onViewStateRestored method is never ever called.
Q: So what's wrong?
public class MapFragment extends Fragment implements OnMapReadyCallback {
private final String SAVED_CAMERA_STATE = "state_map_camera";
private GoogleMap map;
private CameraPosition camera;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
SupportMapFragment mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (savedInstanceState != null)
camera = savedInstanceState.getParcelable(SAVED_CAMERA_STATE);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (map == null)
return;
// save camera state
outState.putParcelable(SAVED_CAMERA_STATE, map.getCameraPosition());
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState == null)
return;
camera = savedInstanceState.getParcelable(SAVED_CAMERA_STATE);
// restore the camera state;
if (map != null && camera != null)
map.moveCamera(CameraUpdateFactory.newCameraPosition(camera));
}
@Override
public void onMapReady(GoogleMap map) {
this.map = map;
// ToDo: add your markers to the map
// restore the camera state
if (camera != null) {
map.moveCamera(CameraUpdateFactory.newCameraPosition(camera));
}
}