When developing an application, there's an opportunity to polish the user experience by using icon animations to define different states of a particular interaction.
On Android, icon animations can be performed using AnimatedVectorDrawable
s, which provide us with a way to play them manually. However, when dealing with several icon animations, and when tying them to states, it results in a lot of boilerplate code. With this in mind, another option Android provides is AnimatedStateListDrawable
s.
AnimatedStateListDrawable
is similar to StateListDrawable
, as it allows us to change a drawable based on its state, but instead of simply swapping them, AnimatedStateListDrawable
can define AnimatedVectorDrawable
s to animate changes between states.
Let’s take a look at an example. We start by implementing a StateListDrawable
and then convert it to an AnimatedStateListDrawable
.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_home_selected" android:state_checked="true" />
<item android:drawable="@drawable/ic_home_unselected" android:state_checked="false" />
</selector>
We create our StateListDrawable
using the selector
tag and define the items to change the drawable based on the states defined. This would create a drawable that would switch the home icon based on the checked state of the view.
Now let’s animate the drawable transition, we start by changing the root tag to animated-selector
and define a transition
that uses AnimatedVectorDrawable
.
<?xml version="1.0" encoding="utf-8"?>
<animated-selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/selected"
android:drawable="@drawable/ic_home_selected"
android:state_checked="true" />
<item
android:id="@+id/unselected"
android:drawable="@drawable/ic_home_unselected"
android:state_checked="false" />
<transition
android:drawable="@drawable/avd_home_unselected_to_selected"
android:fromId="@id/unselected"
android:toId="@id/selected" />
<transition
android:drawable="@drawable/avd_home_selected_to_unselected"
android:fromId="@id/selected"
android:toId="@id/unselected" />
</animated-selector>
That’s it, now whenever our view state changes the AnimatedStateListDrawable
will automatically run the drawable transition to animate the icon.
You can find the sample source code here. In the sample app, I have used the AnimatedStateListDrawable
with BottomNavigationView
to animate icons when the selected page changes.
Wan’t to learn more?
AnimatedStateListDrawable
When developing an application, there's an opportunity to polish the user experience by using icon animations to define different states of a particular interaction.