Sobes.tech
Middle

Why is it not recommended to change the layout during animation?

sobes.tech AI

Answer from AI

Changing the View hierarchy during animation can lead to the following issues:

  • Rendering of outdated state: The rendering system works with cached data about the View structure. Changing the layout "on the fly" can cause the animation to apply transformations to incorrect coordinates or sizes, as the renderer has not yet updated its View hierarchy model.
  • Frame skips (Jank): Layout change operations, such as recalculating sizes and positions (measure and layout phases), require significant computational resources. Performing these operations during an animation, which itself requires smooth UI updates in each frame, can overload the main thread, cause frame skips, and consequently "stutter" in the animation.
  • Visual artifacts: Inconsistencies between the current state of the View hierarchy and the one used by the animator can manifest as flickering, jumps, or incorrect display of elements on the screen.
  • Debugging complexity: Catching and fixing errors related to the synchronization of layout changes and animation can be quite challenging due to unpredictable behavior and timing dependencies.

Instead of changing the layout during animation, it is preferable to use the following approaches:

  • Animation on properties: Animate View properties such as translationX, translationY, scaleX, scaleY, alpha, rotation. These properties are changed independently of the measure and layout phases.
  • ConstraintLayout with Keyframes: Use ConstraintLayout and animate changes in ConstraintSet. This allows smooth transitions between different element positioning states.
  • Animate the parent View: If you need to animate a group of Views, animate their common parent (e.g., ViewGroup).
  • AnimationDrawable or AnimatedVectorDrawable: For complex, predefined animations, use drawable resources.
Why is it not recommended to change the layout during… - sobes.tech