Saturday, May 17, 2014

Why Overlay in android and how overlay works in android

What is Overlay?

Generally overlay can be defined as 
 
"Cover the surface of a thing with a coating." 
 
In Android:

"Overlay is the individual items placed on the map."

There are many ways to get custom graphics (drawables) to appear in a view. You can set a background drawable if that's what you want, or you can use an ImageView, or you can create a custom View subclass and override onDraw(). Or if you want to draw them over the children in a layout, you can override the layout and override dispatchDraw() to draw them after all of the children (after a call to super.dispatchDraw()). But sometimes you just want something simpler: ViewOverlay.

View Overlay
ViewOverlay is a class that we can find in Android since its version 4.3 (API version 18) that provides a transparent layer on top of a View, to which you can add visual content and that does not affect the layout hierarchy.

How does it work?

You just have to call the getOverlay() method from any View of your app to get its ViewOverlay, or a ViewGroupOverlay if you are calling this method from some ViewGroup object, but both of them uses the same concept.

Once you got it, you can add any View or Drawable that you want to show in this overlay calling add(Drawable drawable) method on ViewOverlay, or add(View view) on ViewGroupOverlay.

ViewOverlay API is so simple, aside from add(Drawable drawable), we can also find clear() and remove(Drawable drawable). These are the only methods that we have to use to handle the views that we move to our ViewOverlays.

Why should I use ViewOverlay?

Well, for now everything that I came up to my mind to do with this new API can be done using RelativeLayout and  a bit of tricky & ugly code. But this lets us to do that things in a friendly way.

Essentially, this component is visual-only, so views attached to a ViewOverlay will not respond to any touch or tap event. ViewOverlay mechanism was conceived to be used combined with stuff like animations.

"Using ViewOverlays we can animate views through other layouts in view hierarchy, even if they are not any of its parents."
So when some of these animations ends, we should have to call clear() or remove(Drawable drawable) methods, to remove the view from our ViewOverlay to keep it clean and avoid memory leaks.

This is only for API 18+, although we hope it will be backported at some support library in the near future.

Overlay Example