Android RecyclerView Layout Animations With Examples

In this tutorial, we’ll be discussing and implementing RecyclerView Layout Animations in our Android Application.

Android RecyclerView Layout Animations

There are many ways to Animate rows in a RecyclerView.
Two commonly tried and tested ways are :

  • Using ItemAnimators. – Read this tutorial.
  • Setting animation on each row in the onBindViewHolder in the Adapter class

There’s another lesser-known but more efficient way of animating a RecyclerView using Layout Animations.

We can directly pass the animation resource asset in the XML on the attribute android:layoutAnimation.

The anim resource passed must contain <layoutAnimation> as the root tag.
layoutAnimation is valid on all other layouts as well besides RecyclerView.

Let’s start by defining some basic Animations in the res | anim folder in our Android Studio Project.

down_to_up.xml

up_to_down.xml

left_to_right.xml

right_to_left.xml

Now let’s create the layoutAnimation for each of these animation sets.

layout_animation_down_to_up.xml

layout_animation_up_to_down.xml

layout_animation_left_to_right.xml

layout_animation_right_to_left.xml

Setting Layout Animation in XML and Programmatically

We can set the Layout Animation on RecyclerView in XML in the following way:

Programmatically:

In order to re-run the animation or in case the data set of the RecyclerView has changed the following code is used:

Project Structure

android-recyclerview-layout-animation-project-structure

Code

The code for the activity_main.xml layout is given below:

FloatingActionButton is used to toggle through the different layout animations.

The layout for the rows of RecyclerView is defined in item_row.xml as shown below:

The code for the RecyclerViewAdapter.java class is given below.

The code for the MainActivity.java class is given below:

runAnimationAgain method is used to loop through each animation and run them on the RecyclerView again.

The output of the above application in action is given below:

android recyclerview layout animation output 1

Now if we apply a GridLayoutManager as the layout manager we’ll get the following output:

android recyclerview layout animation output grid

The above layout animation is not grid layout animation. It’s animating each row at a time.
This is incorrect. The RecyclerView LayoutAnimation defaults for Lists only.
In order to do Grid Layout Animation, we need to customize the recycler view.
We’ll do that in the next tutorial.

That brings an end to this tutorial. You can download the project from the link below:

By admin

Leave a Reply