How to animate RecyclerView items when adapter is initialized (in order)?

After you call setAdapter you can run following:

recyclerView.getViewTreeObserver().addOnPreDrawListener(
        new ViewTreeObserver.OnPreDrawListener() {

            @Override
            public boolean onPreDraw() {
                recyclerView.getViewTreeObserver().removeOnPreDrawListener(this);

                for (int i = 0; i < recyclerView.getChildCount(); i++) {
                    View v = recyclerView.getChildAt(i);
                    v.setAlpha(0.0f);
                    v.animate().alpha(1.0f)
                            .setDuration(300)
                            .setStartDelay(i * 50)
                            .start();
                }

                return true;
            }
        });

Example shows simple alpha animation, but you can run what you want in the loop and adjust interpolator, duration and start delay.


Easy way is set in xml in your RecyclerView tag (or in code like above comment)

android:layoutAnimation="@anim/slide_left_in_layout_anim"

slide_left_in_layout_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:animation="@android:anim/slide_in_left"
    android:delay="10%"
    android:animationOrder="normal"
/>

Note: this animation only excuted when first time load data, if you want add animation when add/remove/move an item, take a look at ItemAnimator and i think this post will help you know something that helpful


I have decided to use a different approach from what Niko suggested earlier. His method works great and is very easy, but it was causing some buggy animations when adding and removing items (as can be seen here).

So I decided to try a different approach and use a layout animation controller. Here's the code I used to achieve the same result.

public void initialRVAnimation() {

    AnimationSet set = new AnimationSet(true);

    // Fade in animation
    Animation fadeIn = new AlphaAnimation(0.0f, 1.0f);
    fadeIn.setDuration(400);
    fadeIn.setFillAfter(true);
    set.addAnimation(fadeIn);

    // Slide up animation from bottom of screen
    Animation slideUp = new TranslateAnimation(0, 0, Utils.getScreenHeight(this), 0);
    slideUp.setInterpolator(new DecelerateInterpolator(4.f));
    slideUp.setDuration(400);
    set.addAnimation(slideUp);

    // Set up the animation controller              (second parameter is the delay)
    LayoutAnimationController controller = new LayoutAnimationController(set, 0.2f);
    rv.setLayoutAnimation(controller);

    // Set the adapter
    adapter = new ItemAdapter(data, this);
    recyclerView.setAdapter(adapter);
}

Tags:

Android