Android: Save variables and settings on rotation

后端 未结 2 902
情歌与酒
情歌与酒 2021-01-25 02:19

Is there a way to save variables that are being changed in the code, when the screen rotates? Thank you in advance

2条回答
  •  心在旅途
    2021-01-25 02:54

    Expanding on GSala's answer, this is sort of how I'd do it:

    @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);
    }
    

    Then in your onCreate you can get values like this:

    @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));
            }
    }
    

    This way, you don't have to Override onRestoreInstanceState as well. Also, this can be done with just about any variable or object, not just strings.

    See this documentation for more information.

提交回复
热议问题