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

為 Android 輸入框加上抖動動畫

編輯:關於 Android 程式設計

密碼輸入錯誤時讓輸入框左右晃一下,是很常見又很好用的回饋手法。Android 的 Translate 動畫加上 CycleInterpolator,幾行 XML 就能做到。

一、Java 端啟動動畫

Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
findViewById(R.id.pw).startAnimation(shake);

二、res/anim/shake.xml

<translate xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="5000"
    android:fromXDelta="0"
    android:interpolator="@anim/cycle_7"
    android:toXDelta="10" />

三個參數的意義:duration 是整段動畫的時間(毫秒),fromXDelta 與 toXDelta 決定水平位移的起點與終點,也就是抖動幅度。

三、res/anim/cycle_7.xml

<cycleInterpolator xmlns:android="https://schemas.android.com/apk/res/android"
    android:cycles="50" />

CycleInterpolator 會讓位移在起點與終點之間來回擺盪,cycles 就是擺盪次數。次數越多看起來越急促,這也是檔名叫 cycle_7 由來——官方範例用的是 7 次。

四、配置檔中的輸入框

<EditText android:id="@+id/pw"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="50dip"
    android:clickable="true"
    android:singleLine="true"
    android:password="true" />

參數怎麼調

把 duration 設成 5000、toXDelta 設成 10,晃起來會又慢又幾乎看不出來,示範用可以,實際產品上建議 duration 落在 300 到 600 毫秒、cycles 設 3 到 7,幅度則視你要的「激烈程度」微調。抖動這種效果一旦過頭,使用者只會覺得界面在故障。

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