androidandroid-animationandroid-viewviewswitcherviewanimator

What is the current, new alternative to ViewAnimator?


Background

I have been using ViewAnimator/ViewSwitcher for a long time.

The most common use case I had was to switch from loading phase to content phase, or between phases of a wizard, and even having an error phase sometimes.

The problem

When I suggested adding a nice extension function to "android-ktx" repository (here), I was told:

ViewAnimator is not an API we actively recommend to animate views. It's based on the old animation system and we don't want to promote its use in this library.

What I've tried

I've looked at articles of ViewAnimator and ViewSwitcher, including the docs. It doesn't say there that it was replaced/deprecated, or that it's recommended to use something else instead.

The questions

  1. What has replaced ViewAnimator? Is he talking about transitions?

  2. What are the advantages and disadvantages compared to ViewAnimator?

  3. Given a ViewAnimator with some views, how would it be converted to the newer solution, including the switching between the states?


Solution

  • I guess one possible alternative is using transitions of ConstraintLayout , as shown here .

    To implement, it seems it has to use 2 similar layouts, with same ids for each view, and then you can switch between the phases, as such:

    class MainActivity : AppCompatActivity() {
        private var show = false
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.circuit)
            backgroundImage.setOnClickListener {
                if(show)
                    hideComponents() // if the animation is shown, we hide back the views
                else
                    showComponents() // if the animation is NOT shown, we animate the views
            }
        }
    
        private fun showComponents(){
            show = true
            val constraintSet = ConstraintSet()
            constraintSet.clone(this, R.layout.circuit_detail)
            val transition = ChangeBounds()
            transition.interpolator = AnticipateOvershootInterpolator(1.0f)
            transition.duration = 1200
            TransitionManager.beginDelayedTransition(constraint, transition)
            constraintSet.applyTo(constraint)
        }
    
        private fun hideComponents(){
            show = false
            val constraintSet = ConstraintSet()
            constraintSet.clone(this, R.layout.circuit)
            val transition = ChangeBounds()
            transition.interpolator = AnticipateOvershootInterpolator(1.0f)
            transition.duration = 1200
            TransitionManager.beginDelayedTransition(constraint, transition)
            constraintSet.applyTo(constraint)
        }
    }