Last active
May 26, 2020 10:10
-
-
Save DDihanov/6624925ced3b4db6f4ce6cbe1704a891 to your computer and use it in GitHub Desktop.
Chain Animate ConstraintLayouts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.transition.AutoTransition | |
import android.transition.TransitionManager | |
import androidx.constraintlayout.widget.ConstraintLayout | |
import androidx.constraintlayout.widget.ConstraintSet | |
import androidx.core.transition.doOnEnd | |
//convenience method to animate several constraint layouts one after another | |
//important to only pass in the constraint layout LAYOUT FILE ids | |
//if you have a case where the start view does not have a root which is a ConstraintLayout, then for the next | |
//layouts which are going to act as frames, leave the parent out and only have the constraint layout as root | |
//this advice was taken from https://medium.com/@harivigneshjayapalan/well-using-constraintset-within-the-scrollview-is-not-encouraged-position-and-behaviour-may-ac6a2c6facc3 | |
fun ConstraintLayout.chainAnimate(@LayoutRes layouts: List<Int>) { | |
val layoutIds = layouts.toMutableList() | |
val iterator = layoutIds.iterator() | |
val start = iterator.next() | |
val transition = if (iterator.hasNext()) { | |
iterator.remove() | |
val transition = AutoTransition() | |
transition.doOnEnd { | |
this.chainAnimate(layoutIds) | |
} | |
transition | |
} else { | |
null | |
} | |
this.constructSetAndAnimate(start, transition) | |
} | |
fun ConstraintLayout.constructSetAndApply( | |
layoutId: Int | |
) { | |
val set = ConstraintSet() | |
set.clone(context, layoutId) | |
set.applyTo(this) | |
} | |
fun ConstraintLayout.constructSetAndAnimate( | |
layoutId: Int, | |
transition: AutoTransition? = null | |
) { | |
val set = ConstraintSet() | |
set.clone(context, layoutId) | |
TransitionManager.beginDelayedTransition(this, transition) | |
set.applyTo(this) | |
} | |
// example usage in a Fragment: | |
//where fragment_root is the ConstraintLayout you want to animate | |
//also important to call this with post, otherwise animation gets stuck | |
//fragment_root.post { | |
// fragment_root.chainAnimate( | |
// mutableListOf( | |
// R.layout.fragment_a, | |
// R.layout.fragment_b, | |
// R.layout.fragment_c | |
// ) | |
// ) | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment