首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android ImageView 往復旋轉動畫實現:AnimationListener 鏈式播放兩個 RotateAnimation

     編輯:程式設計綜合問答

需求:ImageView 先順時針旋轉 20°→50°,再逆時針 50°→20°,無限循環,模擬搖擺效果。

方案:兩個 RotateAnimation + AnimationListener 相互觸發

// 1. 定義兩個動畫
RotateAnimation animClockwise = new RotateAnimation(20f, 50f,
    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
animClockwise.setInterpolator(new LinearInterpolator());
animClockwise.setDuration(300);
animClockwise.setFillAfter(true);

RotateAnimation animCounterClockwise = new RotateAnimation(50f, 20f,
    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
animCounterClockwise.setInterpolator(new LinearInterpolator());
animCounterClockwise.setDuration(300);
animCounterClockwise.setFillAfter(true);

// 2. 鏈式監聽器
animClockwise.setAnimationListener(new Animation.AnimationListener() {
    @Override public void onAnimationStart(Animation a) {}
    @Override public void onAnimationRepeat(Animation a) {}
    @Override public void onAnimationEnd(Animation a) {
        imageView.startAnimation(animCounterClockwise); // 結束時啟動反向
    }
});

animCounterClockwise.setAnimationListener(new Animation.AnimationListener() {
    @Override public void onAnimationStart(Animation a) {}
    @Override public void onAnimationRepeat(Animation a) {}
    @Override public void onAnimationEnd(Animation a) {
        imageView.startAnimation(animClockwise); // 結束時啟動正向
    }
});

// 3. 啟動
imageView.startAnimation(animClockwise);

關鍵點

  • setFillAfter(true) 保持動畫結束狀態,避免跳變。
  • 使用 RELATIVE_TO_SELF, 0.5f 以圖片中心為旋轉軸。
  • LinearInterpolator 保證勻速,視覺更自然。
  • 監聽器中**直接啟動下一個動畫**,形成閉環。

現代替代:ObjectAnimator / AnimatedVectorDrawable

// ObjectAnimator 無限往復
ObjectAnimator animator = ObjectAnimator.ofFloat(imageView, "rotation", 20f, 50f);
animator.setDuration(300);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setRepeatMode(ValueAnimator.REVERSE); // 關鍵:反向播放
animator.setInterpolator(new LinearInterpolator());
animator.start();

優點:代碼極簡、硬件加速、支持暫停/恢復/反向、屬性動畫體系統一。

總結

舊版 View Animation 用雙動畫鏈式監聽實現往復,新項目**首選 ObjectAnimator REVERSE 模式**,一行代碼解決。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved