Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Making a View Shake

Author: Ian Darwin
Published? true -- FormatLanguage: W

Problem:

You want a View component to shake for a few seconds to catch the user's attention.

Solution:

Create an animation in the XML, then call the View object's startAnimation(), using the convenience routing loadAnimation() to load the XML.

Discussion:

The Animation specification is created in XML files in the anim directory. In this example I want the text entry field to be able to shake either left-to-right (to emulate a person shaking their head side-to-side, meaning "no" or "I disagree" in many parts of the world) or up and down (a person nodding agreement). So I create two animations, horizontal.xml and vertical.xml. Here is horizontal.xml:

<?xml version="1.0" encoding="utf-8"?>
<translate
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:fromXDelta="0"
	android:toXDelta="10"
	android:duration="1000"
	android:interpolator="@anim/cycler"
	/>

The file vertical.xml is identical except it uses fromYDelta and toYDelta.

The Interpolator - the function that drives the animation - is contained in another file, cycler.xml, shown below.

<?xml version="1.0"?>
<cycleInterpolator
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:cycles="5"/>

To apply one of the two animations to a View component, you need a reference to it. You can of course use the common findViewById(R.id.XXX). You can also use the Activity method getCurrentFocus() if you are dealing with the current input (focus) view component; this avoids coupling to the name of a particular component, if you know that your animation will always apply to the current input object. In my code I know this is true because the animation startup is done in an onClick() method. Thirdly, you could use the View that is passed into the onClick() method, but that would make the Button shake, not the text field.

I won't show the whole application, but here is the onClick() method which contains all the animation code:

@Override
public void onClick(View v) {
	String answer = answerEdit.getText().toString();
	if ("yes".equalsIgnoreCase(answer)) {
		getCurrentFocus().startAnimation(
		AnimationUtils.loadAnimation(getApplicationContext(), 
		R.anim.vertical));
		return;
	}
	if ("no".equalsIgnoreCase(answer)) {
		getCurrentFocus().startAnimation(
		AnimationUtils.loadAnimation(getApplicationContext(), 
		R.anim.horizontal));
		return;
	}
	Toast.makeText(this, "Try to be more definite, OK?",
		Toast.LENGTH_SHORT).show();
}

The shaking effect is convenient for drawing the user's attention to an input that is incorrect, but it can easily be overdone. Use judiciously!

No records found.