需求:ImageView 先順時針旋轉 20°→50°,再逆時針 50°→20°,無限循環,模擬搖擺效果。
// 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 無限往復
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 模式**,一行代碼解決。