MfA tricks #7 - eye-candy using layout animations
Since Android 3.0 (API level 11), a lot of effort went into improving the amount of eye-candy in the system while making it easier for third party developers to do the same for their applications.
One of such improvements is to provide an easy way to automatically add animation to existing ViewGroup
elements (i.e. every layout objects) without having to code them up.
Indeed, when using the android:animateLayoutChanges attribute with a ViewGroup
, a set of default animations are registered on its children views during layout changes.
By default, visibility and size modifications are taken into account. The first produce a fadein/fadeout effect and the second produces a slidein/slideout animation.
These two default effects can be used together with a LinearLayout
to make a nice transition between two states of the same widget:
In the video, my widget has two different presentation modes, one for user selection and the other for drag-and-drop interaction. The latter mode is triggered by an user action (starting the drag).
Here is the relevant part of my layout XML for the widget skeleton:
The outer LinearLayout
is the one that contains the android:animateLayoutChanges
attribute. Both widget modes are also LinearLayout
objects.
Since the first mode is the one shown by default, its layout height is set to wrap_content
whereas the second mode layout is artificially hidden by setting its height to 1 pixel.
To go from mode 1 to mode 2, I use the following code in the drag started event handler:
And to go the other way, we simply restore the XML state we had beforehand with a similar code: