Search code examples
javaandroidandroid-motionlayout

How to Loop a MotionLayout Animation?


I'm trying out the MotionLayout and from what I've learned it seems to be used for transitioning from point A to B. Is there a looping property that goes from A to B and restarts?

I haven't tried anything out yet. Just doing my research before actually coding it.


Solution

  • The answer @hoford provided does something similar, but I wanted something simple.

    This is my approach:

    MotionLayout motionLayout = findViewById(R.id.motionLayout);
    
            motionLayout.transitionToEnd();
    
            motionLayout.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(!looped)
                        motionLayout.transitionToStart();
    
                    else
                        motionLayout.transitionToEnd();
    
                    looped = !looped;
                }
    
                @Override
                public void onTransitionTrigger(MotionLayout motionLayout, int i, boolean b, float v)
                {
    
                }
            }); 
    

    Where looped starts off as false. It does this quick jitter on the 1st trigger of onTransitionCompleted cause it tries to go from start to end and from end to start sort of at the same time(don't ask me why. It just does). But, it works fine because it's hardly noticeable for what I want it for.