Search code examples
androidandroid-motionlayout

MotionLayout - Animate without event


In my scene that I want to animate I have some animation that is triggered by an on click event. But I also have some bits that I want to animate in the background and on repeat that are not triggered by anything. Can I use motionlayout to create animation that just loops and needs no trigger?


Solution

  • As far as I know you can't. MotionLayout is designed to create an easier way to animate transitions between two scenes, and not to be used as an animator for views.

    But you can always use a work around (which is not "pretty", yeah I know):

    class AnimationTask(val motionLayout: MotionLayout, val handler: Handler) : Runnable {
    
        override fun run() {
            if (fragmentOrActivityIsDestroyed) {
                return
            }
    
            when (motionLayout.currentState) {
                R.id.sceneEnd -> motionLayout.transitionToStart()
                R.id.sceneStart -> motionLayout.transitionToEnd()
            }
    
            handler.postDelayed(this, yourDelay)
        }
    }
    
    Handler(Looper.getMainLooper()).apply {
       postDelayed(AnimationTask(motionLayout, this), yourDelay)
    }
    

    Edit

    As stated here:

    This Layout supports transitions between constraint sets defined in MotionScenes

    A MotionLayout is a ConstraintLayout which allows you to animate layouts between various states.