萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 實現 View 抖動動畫效果:TranslateAnimation + CycleInterpolator

效果預覽

輸入框驗證失敗、密碼錯誤、登錄按鈕點擊無效時,讓對應 View 發生水平「抖動」提示用戶,是提升表單交互體驗的經典手法。

核心原理

  • TranslateAnimation:定義 X/Y 軸平移位移
  • CycleInterpolator:以正弦波形式重複動畫,android:cycles="7" 表示來回震盪 7 個週期
  • 組合兩者即可產生「左右抖動」視覺效果

步驟 1:定義動畫資源文件

在 res/anim/ 目錄下建立兩個 XML:

shake.xml — 位移動畫

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="https://schemas.android.com/apk/res/android"
    android:fromXDelta="0"
    android:toXDelta="10"
    android:duration="500"
    android:interpolator="@anim/cycle_7" />

關鍵屬性:

  • fromXDelta="0":起始位置 (相對自身 0%)
  • toXDelta="10":終止位移 10 像素 (可改為 10% 相對寬度)
  • duration:單次動畫時長,配合 cycles 總時長 = duration × cycles × 2
  • interpolator:引用下方的 CycleInterpolator

cycle_7.xml — 週期插值器

<?xml version="1.0" encoding="utf-8"?>
<cycleInterpolator xmlns:android="https://schemas.android.com/apk/res/android"
    android:cycles="7" />

cycles="7" 表示完整正弦波 7 個週期 (即左→右→左 算 1 個週期,共 7 次來回)。可根據體感調整 5~10 之間。

步驟 2:代碼中加載並啟動

// 在 Activity/Fragment 中
Animation shakeAnim = AnimationUtils.loadAnimation(this, R.anim.shake);
targetView.startAnimation(shakeAnim);

Kotlin 擴展函數一鍵調用

fun View.shake(cycles: Int = 7, distancePx: Float = 10f, duration: Long = 500) {
    val shake = TranslateAnimation(0f, distancePx, 0f, 0f).apply {
        duration = duration
        interpolator = CycleInterpolator(cycles.toFloat())
        fillAfter = false
    }
    startAnimation(shake)
}

// 使用
editText.shake()
loginButton.shake(cycles = 5, distancePx = 15f)

進階:純代碼構建 (無 XML)

fun createShakeAnimation(cycles: Int = 7, distance: Float = 10f, duration: Long = 500): Animation {
    return TranslateAnimation(0f, distance, 0f, 0f).apply {
        this.duration = duration
        interpolator = CycleInterpolator(cycles.toFloat())
        repeatCount = 0
        fillAfter = false
    }
}

常見問題與優化

  1. 抖動幅度過大/過小:調整 toXDelta (像素) 或改用百分比 10% 適配不同螢幕密度
  2. 動畫結束後 View 位置偏移:確保 fillAfter=false (默認),或動畫結束後 view.clearAnimation()
  3. 頻繁觸發疊加:啟動前 view.clearAnimation() 或檢查 view.animation?.hasEnded() == false 防重入
  4. 性能:TranslateAnimation 運行在 UI 線程,極輕量;避免在列表項大量並發啟動
  5. 無障礙:搭配 announceForAccessibility("輸入有誤") 讓 TalkBack 用戶也能感知

替代方案:Property Animation (API 12+)

現代開發推薦使用 ObjectAnimator,可直接操作 translationX 屬性,支持更靈活的鏈式調用:

ObjectAnimator.ofFloat(view, "translationX", 0f, 10f, -10f, 10f, -10f, 10f, -10f, 10f, 0f)
    .setDuration(500)
    .setInterpolator(CycleInterpolator(7f))
    .start()

優點:硬件加速、可暫停/反轉、與 ViewPropertyAnimator 鏈式調用無縫銜接。

總結

利用 TranslateAnimation + CycleInterpolator 只需兩個微小 XML 即可實現經典抖動效果,零依賴、兼容性極佳 (API 1+)。新項目建議改用 ObjectAnimator 獲得更強控制力,但舊代碼維護或極簡場景下,XML 方案依然實用優雅。

copyright © 萬盛學電腦網 all rights reserved