Search code examples
androidandroid-lifecycleorientation-changesandroid-activityandroid-orientation

Handle states of orientation changes


How can I handle all states of orientation event occurs?

Something like:

  • before starting (save some screen states)
  • when happening (animation purposes)
  • after it's happen (load the screen state)

I know that onConfigurationChanged can handle orientation changes. And I tried this:

    public void onConfigurationChanged(Configuration cfg) {
        saveState();

        super.onConfigurationChanged(cfg);

        loadState();
    }

On saveState I store the lastIndex viewed on the Gallery on SharedPreferences. On loadState I get the lastIndex from the SharedPreferences and make it as the current on the Gallery.

I tried also put loadState in the onResume method but it's not called after the orientation change occurs.


Solution

  • before starting (save some screen states)

    Use onSaveInstanceState() and/or onRetainNonConfigurationInstance() and/or a fragment on which you have called setRetainInstance(true)

    when happening (animation purposes)

    That is handled by the OS.

    after it's happen (load the screen state)

    Use onRestoreInstanceState() and/or getLastNonConfigurationInstance() (if you went the fragment route, your data is just naturally still there)

    I know that onConfigurationChanged can handle orientation changes.

    @EightEight's answer covers this nicely.