【问题标题】:Android: Save variables and settings on rotationAndroid:在旋转时保存变量和设置
【发布时间】:2015-08-20 15:01:03
【问题描述】:

当屏幕旋转时,有没有办法保存代码中正在更改的变量?提前谢谢你

【问题讨论】:

标签: android screen-rotation


【解决方案1】:

您可以在停止活动时将值保存到 instanceState Bundle 中,并在启动活动时将其恢复。像这样:

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    // Read values from the "savedInstanceState"
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    // Save the values you need into "outState"
    super.onSaveInstanceState(outState);
}

【讨论】:

    【解决方案2】:

    扩展 GSala 的答案,这就是我的做法:

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        String someString = "this is a string";
        savedInstanceState.putString(CONSTANT_STRING, someString);
        //declare values before saving the state
        super.onSaveInstanceState(savedInstanceState);
    }
    

    然后在你的 onCreate 你可以得到这样的值:

    @Override
        public void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addContentView(R.layout.view);
    
            //Make sure to do this check otherwise someString will
            //cause an error when your activity first loads!
            if (savedInstanceState != null){
                //Do whatever you need with the string here, like assign it to variable.
                Log.d("XXX", savedInstanceState.getString(STRING_CONSTANT));
            }
    }
    

    这样,您也不必重写 onRestoreInstanceState。此外,这几乎可以使用任何变量或对象来完成,而不仅仅是字符串。

    更多信息请参见this documentation

    【讨论】:

      猜你喜欢
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多