androidandroid-animationandroid-motionlayout

How to save/restore state of MotionLayout on activity rotation


Steps to reproduce: Run an activity with MotionLayout inside it Transition to a non-initial state Rotate the device or enable/disable dark mode

Observed: The MotionLayout is in it's initial state Expected: The MotionLayout is in the state that was shown before the rotation

Should I put the id of the state inside the savedInstanceState, and then transition to that state (with 0 duration, so it is instantaneous) inside onCreate? This approach I think would work but feels a bit hacky, does anyone know a better solution to this problem?

Here's a recording of the problem: enter image description here


Solution

  • MotionLayout does not automatically save its state. The state of the layout can be quite complex.

    The most generic way to save the basic stat of a MotionLayout is to save the bundle returned by getTransitionState() and then call setTransitionState(Bundle b) on restore