Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 如何實現 iPhone 風格的圖片抖動動畫(按鈕與 EditText)

編輯:關於 Android 程式設計

要給按鈕做抖動效果,可以在 res 下建立 anim 資料夾,新增一個 button_shake.xml:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="120"
    android:fromDegrees="-3"
    android:pivotX="100%"
    android:pivotY="100%"
    android:repeatCount="infinite"
    android:repeatMode="reverse"
    android:toDegrees="3" />

在程式碼中載入動畫:

final ImageButton button = (ImageButton) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Animation shake = AnimationUtils.loadAnimation(AnimationTest.this, R.anim.button_shake);
        shake.reset();
        shake.setFillAfter(true);
        button.startAnimation(shake);
    }
});

若要給 EditText 做一個橫向抖動的效果,可搭配 cycleInterpolator 使用。先定義加速器動畫:

<?xml version="1.0" encoding="utf-8"?>
<!-- 動畫從開始到結束,變化率為循環給定次數的正弦曲線 -->
<cycleInterpolator xmlns:android="https://schemas.android.com/apk/res/android"
    android:cycles="20" />

程式碼可這樣載入:

final Button confirm = (Button) findViewById(R.id.btn_confirm);
confirm.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (custom_edittext.getText().toString().equals("jake")) {
            Toast.makeText(AnimationTest.this, "welcome", Toast.LENGTH_LONG).show();
        } else {
            Animation shake = AnimationUtils.loadAnimation(AnimationTest.this, R.anim.shake_x);
            custom_edittext.startAnimation(shake);
        }
    }
});

透過 rotate 動畫與 cycleInterpolator 的搭配,就能做出類似 iPhone 輸入錯誤時左右抖動的視覺效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved