Android : Save application state on screen orientation change

后端 未结 3 993
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 20:55

I have seen the following links before posting this question

http://www.devx.com/wireless/Article/40792/1954

Saving Android Activity state using Save Instan

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 21:18

    There are 2 ways of doing this, the first one is in the AndroidManifest.xml file. You can add this to your activity's tag. This documentation will give you an in depth explanation, but put simply it uses these values and tells the activity not to restart when one of these values changes.

    android:configChanges="keyboardHidden|orientation|screenSize|screenLayout"
    

    And the second one is: overriding onSaveInstanceState and onRestoreInstanceState. This method requires some more effort, but arguably is better. onSaveInstanceState saves the values set (manually by the developer) from the activity before it's killed, and onRestoreInstanceState restores that information after onStart() Refer to the official documentation for a more in depth look. You don't have to implement onRestoreInstanceState, but that would involve sticking that code in onCreate().

    In my sample code below, I am saving 2 int values, the current position of the spinner as well as a radio button.

     @Override
        public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
            spinPosition = options.getSelectedItemPosition();
            savedInstanceState.putInt(Constants.KEY, spinPosition);
            savedInstanceState.putInt(Constants.KEY_RADIO, radioPosition);
            super.onSaveInstanceState(savedInstanceState);
    
        }
    
        // And we restore those values with `getInt`, then we can pass those stored values into the spinner and radio button group, for example, to select the same values that we saved earlier. 
    
        @Override
        public void onRestoreInstanceState(@NotNull Bundle savedInstanceState) {
            spinPosition = savedInstanceState.getInt(Constants.KEY);
            radioPosition = savedInstanceState.getInt(Constants.KEY_RADIO);
            options.setSelection(spinPosition, true);
            type.check(radioPosition);
            super.onRestoreInstanceState(savedInstanceState);
        }
    

提交回复
热议问题