Android: simple animate layout

There is an easy way to animate a layout status (visible/gone) change in Android. In the xml layout file you have to set true the value “animateLayoutChanges” under the container of the elements will appear/disappear. For example:

In this simple way android will automatically animate any visibility change on your layout; just change the element visibility from visible to gone, or vice versa.

You can also manage the animation, by setting a listener. Let show a simple example to make it all clear.

As you can see it is not very complicated. As familiar you must retrieve the view by findViewById, here it’s the linearLayout object, then you need to get the layoutTransition object, where we will go to add a TransitionListener. Here we have an interface where manage the beginning and the end of the animation and all the possible values to help us to do what we need to. This is showed in the endTransition, where we do something through checking which type of transition is ended.

Before to conclude this little help I show you the only (for my experience) trouble that you could find with this kind of animation. If you have a RecyclerView as child of a layout with the animateLayoutChanges enabled your application will crash while you will start the animation. This is because of an exception throws by the scrollTo method of the RecyclerView class that is called by the parent layout to manage the animation. The simple way to avoid this is to write a class that extend the RecyclerView and override the scrollTo method without throw any exception.

As you see we don’t do anything inside the scrollTo method, just write a string in the error log (it’s not necessary for a correct running). After that we just need to remember to use this class instead of the RecyclerView where and when we need it.

Questo articolo è stato postato in Android