Save state of activity when orientation changes android

前端 未结 4 1975
谎友^
谎友^ 2020-11-28 08:38

I have an aacplayer app and I want to save the state of my activity when orientation changes from portrait to landscape. The TextViews do not appear to be empty, I tried to

4条回答
  •  悲哀的现实
    2020-11-28 09:36

    There are two ways of doing this, the first one is in the AndroidManifest.xml file. You can add this to your activity's tag

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

    Or you can override two methods that will take care of this. This method requires some more effort, but arguably is much better. onSaveInstanceState saves the state of the activity before it's killed, and onRestoreInstanceState restores that information after onStart() Refer to the official documentation for a more in depth look.

    In my sample code below, I am saving 2 int values, the current selection from 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 I am restoring those values with `getInt`, then I can pass those stored values into the spinner and radio button group 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);
        }
    

提交回复
热议问题