Skip to content

Instantly share code, notes, and snippets.

@adammagana
Created October 19, 2020 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adammagana/f4a64aa4fb17c6034807f11901bc18cf to your computer and use it in GitHub Desktop.
Save adammagana/f4a64aa4fb17c6034807f11901bc18cf to your computer and use it in GitHub Desktop.
Helper method for updating constraints on a ConstraintLayout with Transitions.
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.transition.Transition
import androidx.transition.TransitionManager
/**
* Runs the given `updateBlock` on the current `ConstraintSet` and applies them back to the
* [ConstraintLayout].
*
* @param animated Whether or not to run [TransitionManager.beginDelayedTransition] on the next
* frame.
* @param transition The transition to use if `animated` is `true`. Falls back to
* [TransitionManager]'s default [Transition] if null.
* @param updateBlock The block used to updated the [ConstraintLayout]'s current [ConstraintSet].
* @return The updated [ConstraintSet]
*/
fun ConstraintLayout.updateConstraints(
animated: Boolean = true,
transition: Transition? = null,
updateBlock: ConstraintSet.() -> Unit
): ConstraintSet {
// Queue up a transition on the next frame if an animation is requested.
if (animated) {
// TransitionManager will fallback to the default Transition if the given one is null
TransitionManager.beginDelayedTransition(this, transition)
}
// Copy the current constraints
val constraintSet = ConstraintSet().apply { clone(this@updateConstraints) }
// Execute the update block
updateBlock(constraintSet)
// Apply the updated constraints
constraintSet.applyTo(this)
return constraintSet
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment