Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire a Animation with MotionLayout programmatically?

Tags:

android

I have a MotionLayout that does reference to MotionScene and i fire the animation "transition" when an event "OnClick" happen over a View but i want to start the animation immediately my activity is started,how i can achieve it?

Fragment layout

    <androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/authFragment"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.login.authFragment.AuthFragment"
    app:layoutDescription="@xml/step3">

    //whatever


</androidx.constraintlayout.motion.widget.MotionLayout>

MotionScene applied to above View (Fragment layout)

  <MotionScene xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- A transition describes an animation via start and end state -->
    <Transition
        app:constraintSetStart="@+id/start"
        app:constraintSetEnd="@+id/end"
        app:autoTransition="none"
        app:duration="2000">
        <OnClick
            app:targetId="@id/tiedt_email"
            app:clickAction="transitionToEnd" />
    </Transition>

    <!-- Constraints to apply at the start of the animation -->
    ...

    <!-- Constraints to apply at the end of the animation -->
    ...
</MotionScene>
like image 341
Oscar Ivan Avatar asked Dec 04 '25 00:12

Oscar Ivan


1 Answers

You can achieve this by calling transitionToEnd or transitionToStart on your motionLayout inside of your activity. So for example inside of the onCreate method of your activity:

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    authFragment.transitionToEnd

If you only want to do the transition if it hasn't already been done, you can wrap the call to authFragment.transitionToEnd in an if (authFragment.progress != 1.0 and it will only do the transition if it hasn't already happened. If you choose to handle the transition programmatically, I recommend removing the

<OnClick
        app:targetId="@id/tiedt_email"
        app:clickAction="transitionToEnd" />

as it is a little harder to track with multiple places that cause the transition.

like image 155
kjanderson2 Avatar answered Dec 06 '25 14:12

kjanderson2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!