우찬쓰 개발블로그

안드로이드 View Animation 연달아 호출하기 본문

안드로이드/안드로이드 개발

안드로이드 View Animation 연달아 호출하기

이우찬 2022. 5. 23. 22:41
반응형

View에 대한 하나의 애니메이션이 끝나고 다음 애니메이션, 그 다음 애니메이션.. 몇개를 연달아 호출하는 요구사항이 있었다.

공식 안드로이드 라이브러리를 찾다보니.. Listener를 각각 다는 방법 말고는 없는것 같아서 편의성 클래스를 하나 만들었다.

(못찾은 걸수도..)

 

https://gist.github.com/WoochanLee/934893722316a120f9955e4fd637dc4a

 

Android Animation Chain

Android Animation Chain. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

AnimationChain.kt

/**
* 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)
}
}
}

사용 방법

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()

 

찾아헤맨 시간보다 코드짜는 시간이 짧았다는건 함정..

반응형
Comments