Skip to content

Instantly share code, notes, and snippets.

@WoochanLee
Last active May 23, 2022 13:32
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 WoochanLee/934893722316a120f9955e4fd637dc4a to your computer and use it in GitHub Desktop.
Save WoochanLee/934893722316a120f9955e4fd637dc4a to your computer and use it in GitHub Desktop.
Android Animation Chain
/**
* Created by WoochanLee on 2022. 05. 23
* https://gist.github.com/WoochanLee/934893722316a120f9955e4fd637dc4a
*/
class AnimationChain private constructor(builder: Builder) {
private val animation: Animation = builder.firstAnimation
private val targetView: View = builder.targetView
fun startAnimation() {
targetView.startAnimation(animation)
}
class Builder {
private val _animationList: MutableList<Animation> = mutableListOf()
private var _targetView: View? = null
val firstAnimation: Animation
get() {
if (_animationList.isEmpty()) {
throw IllegalStateException("You need to add at least one animation")
}
return _animationList.first()
}
val targetView: View
get() {
return _targetView ?: throw IllegalStateException("You need to call setView(View) first")
}
fun targetView(view: View): Builder {
_targetView = view
return this
}
fun addAnimation(nextAnimation: Animation): Builder {
if (_animationList.isEmpty()) {
_animationList.add(nextAnimation)
return this
}
_animationList.last()
.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) = Unit
override fun onAnimationRepeat(animation: Animation?) = Unit
override fun onAnimationEnd(animation: Animation?) {
_targetView?.startAnimation(nextAnimation)
}
})
_animationList.add(nextAnimation)
return this
}
fun build(): AnimationChain {
if (_targetView == null) {
throw IllegalStateException("You need to call setView(View) first")
}
if (_animationList.isEmpty()) {
throw IllegalStateException("You need to add at least one animation")
}
return AnimationChain(this)
}
}
}
@WoochanLee
Copy link
Author

val animationChain = AnimationChain.Builder()
    .targetView(testView)
    .addAnimation(AnimationUtils.loadAnimation(this, R.anim.test_1))
    .addAnimation(AnimationUtils.loadAnimation(this, R.anim.test_2))
    .addAnimation(AnimationUtils.loadAnimation(this, R.anim.test_3))
    .build()

animationChain.startAnimation()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment