This post is based on Roman Nurik artwork and initial idea. He is a great source on Android application design.
The new GMail app that comes with Android 4.0 is full of interesting UI tricks. If you have ever been on dodgy data connection, you probably have already encountered this one that I call the flash bar:
This bar is used to warn of a non-fatal error in an unobstrusive manner and offer a quick way to retry the operation which failed. If the user actually don’t care about it, the bar will disappear after a small amount of time.
For these cases, it efficiently replaces a normal AlertDialog which is much more costly in term of user interaction.
As such, it’s an excellent pattern to handle most network errors in an app since they happen often, are generally non lethal and can be easily relaunched.
As you can see in the screenshot, flash bars are very similar to normal Toast messages. The problem is that toast messages can never gain the focus and thus you can’t use any interactive UI element (like buttons) inside them, that’s why the bar needs to be a custom XML layout snippet.
First of all, download the following zip containing the 9-patch images and the style definition for the flashbar. Put its content in your application Resources directory (merging the styles.xml file with what you already have).
Next, you will need to tune up a bit the XML layout of the Activity that will contain a flash bar. Essentially, it should look like this:
The overlay trick is achieved by using multiple children in a container FrameLayout which stack them bottom to top on the screen. If you have an existing layout where you want to add a flash bar, the first child LinearLayout can be the one that was enclosing your layout initially.
Now, the code manipulating that bar follows:
You generally instantiate this class after inflating your Activity layout by passing it the LinearLayout of the flash bar as a View like so:
Afterwards, you can use either ShowBar or ShowBarUntil to display the flash bar.
Each of these methods accepts a boolean parameter to disable animation and you can set the text of the bar either by string id or directly by passing a string instance. The callback is the action to be called when the user tap the bar button.