iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 4
2
Software Development

Android animation 30天上手系列 第 4

Day04 View Animation 進階(2)

View animation很簡單很重要,所以這一篇會繼續把View animation 再深入一點:

  • AnimationSet 組合動畫
  • AnimationListener 動畫的監聽
  • interpolator 動畫的加速度

AnimationSet 組合動畫

有時候我們會需要同時有2個動畫一起執行,例如一邊移動位置一邊改變透明度,就可以透過 AnimationSet 組合多個動畫。

步驟1:新增一個動畫組合

val animSet = AnimationSet(true)
animSet.fillAfter = true

步驟2:新增第1個動畫,透明過至0.2

val alphaAnimation = AlphaAnimation(1.0f, 0.2f)
alphaAnimation.duration = 1000

步驟3:新增第2個動畫,x座標增加100,y座標減少100

val translateAnimation = TranslateAnimation(
        0f,
        100f,
        0f,
        -100f)
translateAnimation.duration = 1000

步驟4:將動畫加入AnimationSet動畫組合

//將scaleAnimation加入AnimationSet動畫組合
animSet.addAnimation(alphaAnimation)
//將translateAnimation加入AnimationSet動畫組合
animSet.addAnimation(translateAnimation)

this.image.startAnimation(animSet)

其他動畫設定

動畫結束時,停留的畫面

val animSet = AnimationSet(true)
animSet.fillAfter = true //動畫結束時,畫面停在動畫結束的最後一個畫面
animSet.fillBefore = true //動畫結束時,畫面停在動畫開始的第一個畫面

設定動畫重覆次數

animation.repeatCount = 3 //重覆3次
animation.repeatCount = Animation.INFINITE //重覆無限次

設定動畫重覆方式

animation.repeatMode = Animation.REVERSE //反轉
animation.repeatMode = Animation.RESTART //重新開始

AnimationListener

監聽動畫開始、結束、重覆的事件

animation.setAnimationListener(object : AnimationListener {
    override fun onAnimationStart(animation: Animation) {
        println("動畫開始")
    }

    override fun onAnimationEnd(animation: Animation) {
        println("動畫結束")
    }

    override fun onAnimationRepeat(animation: Animation) {
        println("動畫重覆執行")
    }
})

Interpolator

動畫加速模式

//設定加速模式
animation.interpolator = AccelerateInterpolator()

AccelerateInterpolator 加速
AccelerateInterpolator
DecelerateInterpolator 減速
DecelerateInterpolator
LinearInterpolator 均速
LinearInterpolator
OvershootInterpolator 快速完成動畫、超出再回到結束樣式
OvershootInterpolator
AccelerateDecelerateInterpolator 先加速再減速,預設值
AccelerateDecelerateInterpolator
AnticipateInterpolator 先後退再加速前進
AnticipateInterpolator
AnticipateOvershootInterpolator 先後退再加速前進、超過終點後再回到結束樣式
AnticipateOvershootInterpolator
BounceInterpolator 最後階段
BounceInterpolator
CycleInterpolator 週期
CycleInterpolator

到目前為止介紹了View animation xml寫動畫、程式碼寫動畫,到這篇的動畫組合、動畫監聽、加速度,View animation可說是在Android要使用動畫最基本的方式了。下一篇我們就來用目前所學的來做一個Facebook按讚的動畫效果吧!

FacebookLikeButton

完整程式:
https://github.com/evanchen76/ViewAnimation2


上一篇
Day03 View Animation 進階
下一篇
Day05 動畫練習:Facebook like button
系列文
Android animation 30天上手30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言