How to run animation defind in the Android MotionLayout/MotionScene infinitely?

1.5k views Asked by At

I read this document by Google: Manage motion and widget animation with MotionLayout I have also read a few more doc such as Getting Started with the Motion Editor in Android Studio 4.0

The problem is they both talk about how to start the animation when we click on a View/Button. I want to simulate loading animation but I want to start the anime automatically when I display my view.

I realized that I am able to run the animation using the code below. However, the problem is, transitionToEnd() run the animation once.

So, my questions are:

  1. how to run the animation and put it in the loop? (to have it forever until I stop it.)

  2. Is it possible to run the animation from startToEnd, then endToStart, loop the anime in this way?

private fun displayDamLoadingAnimation() {
        val view = layoutInflater.inflate(R.layout.viewgroup_dam_loading, binding.flDamContainer)
        view.motionContainer.transitionToEnd()
    }
2

There are 2 answers

0
hoford On BEST ANSWER

This is probably bad for users phone but you can do it. One way is to create two transitions :

<Transition
    motion:constraintSetEnd="@+id/end"
    motion:constraintSetStart="@+id/start"
    motion:autoTransition="animateToEnd"
    motion:duration="1000">

<Transition
    motion:constraintSetEnd="@+id/end"
    motion:constraintSetStart="@+id/start"
    motion:autoTransition="animateToStart"
    motion:duration="1000">

But if you want it to Loop not go back and forth

<Transition
    motion:constraintSetEnd="@+id/end"
    motion:constraintSetStart="@+id/start"
    motion:autoTransition="animateToEnd"
    motion:duration="1000">
<Transition
    motion:constraintSetEnd="@+id/end"
    motion:constraintSetStart="@+id/start"
    motion:autoTransition="jumpToStart"
    />
0
Tomer Petel On

You can start the transition programmatically and repeat it back and forth using the transition listener. Not sure if that's the most efficient way but I didn't find any other way

private void animateText(){
    mMotionLayout.setTransitionListener(new MotionLayout.TransitionListener() {
        @Override
        public void onTransitionStarted(MotionLayout motionLayout, int i, int i1) {

        }

        @Override
        public void onTransitionChange(MotionLayout motionLayout, int i, int i1, float v) {

        }

        @Override
        public void onTransitionCompleted(MotionLayout motionLayout, int i) {
            if (motionLayout.getCurrentState() == R.id.start){
                animateText();
            } else {
                mMotionLayout.transitionToStart();
            }

        }

        @Override
        public void onTransitionTrigger(MotionLayout motionLayout, int i, boolean b, float v) {

        }
    });
    mMotionLayout.transitionToEnd();
}

The "trick" is to check the state once the transition is done and either transitionToStart() or re-run the function