1、工具类
enum class AnimationState {
STATE_SHOW,
STATE_HIDE,
STATE_SHOW_UP,
STATE_HIDE_UP,
STATE_SHOW_DOWN,
STATE_HIDE_DOWN,
STATE_SHOW_LEFT,
STATE_HIDE_LEFT,
STATE_SHOW_RIGHT,
STATE_HIDE_RIGHT
}
object AnimationUtils {
fun showOrHideAnimation(view: View, state: AnimationState, duration: Long) {
view?.let {
it.post {
val viewHeight = it.measuredHeight + 50
val viewWidth = it.measuredWidth + 50
var start = 0f
var end = 0f
when (state) {
AnimationState.STATE_SHOW,
AnimationState.STATE_SHOW_UP,
AnimationState.STATE_SHOW_DOWN,
AnimationState.STATE_SHOW_LEFT,
AnimationState.STATE_HIDE_RIGHT -> {
end = 1f
it.visibility = View.VISIBLE
}
else -> {
start = 1f
it.visibility = View.INVISIBLE
}
}
val animationSet = AnimationSet(true)
val alphaAnimation = AlphaAnimation(start, end)
alphaAnimation.duration = duration
alphaAnimation.fillAfter = true
animationSet.addAnimation(alphaAnimation)
getTranslateAnimation(
state,
viewHeight.toFloat(),
viewWidth.toFloat()
)?.let { translateAnimation ->
animationSet.addAnimation(translateAnimation)
}
animationSet.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(p0: Animation?) {
}
override fun onAnimationEnd(p0: Animation?) {
}
override fun onAnimationRepeat(p0: Animation?) {
it.clearAnimation()
}
})
it.animation = animationSet
animationSet.start()
}
}
}
private fun getTranslateAnimation(
state: AnimationState,
viewHeight: Float,
viewWidth: Float
): TranslateAnimation? {
var translateAnimation: TranslateAnimation? = null
when (state) {
AnimationState.STATE_SHOW_UP -> translateAnimation =
TranslateAnimation(0f, 0f, viewHeight, 0f)
AnimationState.STATE_HIDE_UP -> translateAnimation =
TranslateAnimation(0f, 0f, 0f, viewHeight)
AnimationState.STATE_SHOW_DOWN -> translateAnimation =
TranslateAnimation(0f, 0f, -viewHeight, 0f)
AnimationState.STATE_HIDE_DOWN -> translateAnimation =
TranslateAnimation(0f, 0f, 0f, -viewHeight)
AnimationState.STATE_SHOW_LEFT -> translateAnimation =
TranslateAnimation(-viewWidth, 0f, 0f, 0f)
AnimationState.STATE_HIDE_LEFT -> translateAnimation =
TranslateAnimation(0f, -viewWidth, 0f, 0f)
AnimationState.STATE_SHOW_RIGHT -> translateAnimation =
TranslateAnimation(viewWidth, 0f, 0f, 0f)
AnimationState.STATE_HIDE_RIGHT -> translateAnimation =
TranslateAnimation(0f, viewWidth, 0f, 0f)
}
return translateAnimation
}
}
2、使用
显示动画
AnimationUtils.showOrHideAnimation(textView, AnimationState.STATE_SHOW_LEFT, 1000)
隐藏动画
AnimationUtils.showOrHideAnimation(textView, AnimationState.STATE_HIDE_LEFT, 1000)
|