密碼輸入錯誤時,讓輸入框左右晃一下,是使用者再熟悉不過的回饋方式。在 Android 裡實作它只需要兩個 XML 檔與一行 Java 程式碼。
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake); findViewById(R.id.pw).startAnimation(shake);
<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 決定位移幅度,而 interpolator 指向另一個檔,用來決定「來回幾次」。
<cycleInterpolator xmlns:android="https://schemas.android.com/apk/res/android"
android:cycles="50" />
cycles 就是擺盪次數。想讓它晃得更急,把 cycles 調大;想更溫和,就調小。這兩個參數搭配著調,很容易做出「敲一下」與「連續錯誤」兩種不同強度的手感。
<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" />
實務上通常會在 onCreate 裡先把動畫載入成成員變數,避免每次錯誤都重新解析 XML;另外別忘了在 AnimationListener 的 onAnimationEnd 中把焦點交回輸入框,讓使用者可以直接重打。