Let’s say a user is filling out a form, and they accidentally skip a required field. How can we bring this to their attention? Here’s what we did for a safety inspections app:
Showing a Snackbar is easy enough, but the secret sauce is in the error animation. As it turns out, this “shake” animation can be built in about 10 lines of xml! The technique is borrowed from StepStone Tech’s awesome material stepper library (https://github.com/stepstone-tech/android-material-stepper).
Essentially, we are modifying the horizontal position of the view using a CycleInterpolator. All values here can be modified to taste. Here’s the animation xml we used.
/res/anim/two_cycle_interpolator <?xml version="1.0" encoding="utf-8"?> <cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android" android:cycles="2"/> /res/anim/shake_error <?xml version="1.0" encoding="utf-8"?> <translate xmlns:android="http://schemas.android.com/apk/res/android" android:duration="400" android:fromXDelta="0%" android:interpolator="@anim/two_cycle_interpolator" android:toXDelta="8%" />
Now to apply it to a view, it’s as simple as:
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.shake_error); view.startAnimation(animation);
Ta da! Super easy, and a nice user experience.