我在活动中使用片段(v4)。该片段显示了GoogleMap,我想在应用进入后台时保存地图的相机位置/状态,并在相机再次进入前景后恢复相机。
android.support.v4.app.Fragment
摄像机状态保存在 onSaveInstanceState(Bundle)中,并在 onViewStateRestored(Bundle)中恢复。但我想知道这些方法是否正确。为什么?因为当您切换到同一应用程序中的另一个活动时,以及当您返回主屏幕或启动另一个应用程序时,会调用 onSaveInstanceState 。一切安好。但永远不会调用 onViewStateRestored 方法。
问:那有什么不对?
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));
}
}
答案 0 :(得分:0)
Android文档中的示例显示了片段的onActivityCreated()方法中正在恢复的值。请参阅本页底部的示例:http://developer.android.com/guide/components/fragments.html#Lifecycle。