【问题标题】:Android: saving and restoring the state of a fragmentAndroid:保存和恢复片段的状态
【发布时间】:2015-10-06 06:06:00
【问题描述】:

我在活动中使用片段 (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));
    }
}

【问题讨论】:

标签: android android-fragments


【解决方案1】:

Android 文档中的示例显示了在片段的 onActivityCreated() 方法中恢复的值。请参阅本页底部的示例:http://developer.android.com/guide/components/fragments.html#Lifecycle

【讨论】:

  • 是的,但仍然保存...一直被调用并且恢复...从不。
  • 感谢您的提示,但该提示正在保存整个片段,而不仅仅是状态。但无论如何都是个好主意。
猜你喜欢
  • 2013-04-04
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-11
  • 1970-01-01
  • 2011-07-23
相关资源
最近更新 更多