保存mapView状态

时间:2015-11-04 16:17:14

标签: android google-maps

如何在3种情况下保存MapView的状态1)旋转设备2)启动新片段并返回上一步3)启动新片段并旋转设备。以下代码解决了2个事件:

public void onPause() {
    Log.d(TAG, "onPause");
    mMapView.onPause();
    View view = mActivity.getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager)mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    super.onPause();
    cameraPosition = mGoogleMap.getCameraPosition();

}

@Override
public void onResume() {

    Log.d(TAG, "onResume");
    super.onResume();
    mMapView.onResume();
    mMapView.getMapAsync(this);
}

这是1场比赛:

@Override
public void onSaveInstanceState(Bundle outState) {

    Log.d(TAG, "onSaveInstanceState");

    if(mSearchString !=null && !mSearchString.equals("")) {
        outState.putString("search", mSearchString);
    }

    final Bundle mapViewSaveState = new Bundle();

    mMapView.onSaveInstanceState(mapViewSaveState);

    outState.putBoolean("firstStart", false);

    outState.putBundle("mapState", mapViewSaveState);
    super.onSaveInstanceState(outState);
}

但是在3次事件中,mMapView == null和NPE。怎么解决?

2 个答案:

答案 0 :(得分:2)

在更改设备方向时,您必须执行两项主要任务  1>在清单文件的活动中,您必须放置此代码

  android:configChanges="keyboardHidden|orientation|screenSize"

2 - ;你必须覆盖

@Override
protected void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putCharSequence("key", "save the value"  );
}

现在检查创建活动

if(bundle !=null)
{
 String saveValue=bundle.getCharSequence("key");
}

现在在定位后使用saveValue。

答案 1 :(得分:1)

如果您想阻止活动重启,只需将其添加到您的清单。

进入您的活动代码

<activity
android:configChanges="orientation|keyboardHidden|screenSize"
/>

修改

此代码将根据您的方向更改加载布局。

活动

中添加此代码
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.landscapeView);
    } else {
        setContentView(R.layout.portraitView);
    }
}