Animated view positions not retained after navigating back to the fragment

28 Views Asked by At

I have FragmentA with 2 views, View1 and View2. I want to animate swapping their positions horizontally. For that I am using this method:

`private fun animateHorizontalSwap(view1: LinearLayout, view2: LinearLayout) {
    val view1StartX = view1.x
    val view2StartX = view2.x

    val animator = ValueAnimator.ofFloat(0f, 1f)
    animator.apply {
        duration = 350
        interpolator = AnticipateOvershootInterpolator()
        addUpdateListener {
            val fraction = it.animatedFraction
            val view1NewX = view1StartX + fraction * (view2StartX - view1StartX)
            val view2NewX = view2StartX + fraction * (view1StartX - view2StartX)


            view1.x = view1NewX
            view2.x = view2NewX
        }

        doOnEnd { animationInProgress = false }
        start()
    }
}`

This works as expected. View1 was on left side and View2 was on the right side. After calling the method, they will swap positions.

The issue: When I navigate to the FragmentB now and on FragmentB I press back button, I will come back to FragmentA. I want to have the positions of the View1 and View2 as they were when I left the fragment (swapped; View2 to be on the left and View1 to be on the right) but the views positions are reset. Is there a way to make views retain their positions as it was after the animation? To me this sounds like something that should work out of the box. Im not understanding where is the issue.

Does anyone have any suggestion on how this might be fixed?

0

There are 0 best solutions below