Implementing Shake Animation in Android

Animation Configuration

To add a shake effect to a textbox when an error occurs, first add the following 2 XML files in your anim folder:

1. Shake Animation (shake.xml)

This file controls how fast or slow the shake should be and how far it should move from left to right.

<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%"
    android:toXDelta="1%"
    android:duration="500"
    android:interpolator="@anim/cycle" />

2. Cycle Interpolator (cycle.xml)

This file controls how many times you want the shake animation to occur.

<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
    android:cycles="3" />

Implementation

Now, use the below code snippet to add shake animation to textbox in your code.
Following code using shake to grab users attention to an error in the email address field:

1
2
3
4
// Load and apply the shake animation
Animation shake = AnimationUtils.loadAnimation(context, R.anim.shake);
emailText.startAnimation(shake);
errorText.setText("\u2757Invalid email address.");