Pages

Wednesday, May 30, 2012

Android: Notifying user of incorrect input


There are two ways to make the user aware of what input they put in was incorrect. The first one is the easiest which is to use the built-in API for EditText. The second is by using a shake animation. Both options can be combined to make it more awesome.






Setup

Let’s assume we have an EditText which we use in our UI.

Furthermore we have a method showError() which we call when the EditText contains invalid data.

Method 1: setError()


setError()- a method which comes out of the box with the EditText view. When calling this method, the right hand drawable of the EditText will be set to the error icon. When the EditText also has focus, the text you gave to setError() will be shown in a popup. If you don’t like the default error icon, you can also use setError(CharSequence error, Drawable icon) to set your own icon. The routine to show errors can then look like this:


Which will result in errors shown like this:

setError() on Android 2.3.3 Gingerbread

setError() on Android 4.0 ICS

Method 2: Shake animation

A nice way to show the user that, for example, he/she forgot to enter a value for an input. First, we have to define our shake animation. Go to your res folder, create the subfolder anim and place a file shake.xml in it. In this file, create a translation like this:

TranslateAnimations let us move views ond the x or y axis of our screen. Since we want to shake it from left to right, we only apply the translation on the x axis. We move it from zero percent of the view’s width to five percent of the view’s width and let the translation last one second (1000 ms). Furthermore, we use the interpolator cylce_7 wich is placed in anim/cycle_7.xml and looks like the following:

It’s a simple CycleInterpolator. This kind of interpolators express the number of repetitions an animation should do. In our case, we repeat the animation seven times.
Now we only need to apply our shake animation to our EditText every time something incorrect is entered. We can do it like this:


To conclude, the above two methods are better to notify user of incorrect input rather than using Toast or AlertDialog. Remember that both methods can also be combined.
Post taken from http://droid-blog.net/.

No comments:

Post a Comment