How to animate recyclerView on notifyDataSetChanged?

Viewed 461

I have a recyclerview which is a list of folders. When I click on an item, the folders/files inside that folder is the new list. I want to play animation of sliding out the old list and sliding in the new list. It should look like entering or leaving a directory.

I have implemented it like this:

// rv : RecyclerView

rv.startAnimation(AnimationUtils.loadAnimation(context, R.anim.slide_out_to_left))
adapter.list = list
rv.notifyDataSetChanged()
rv.startAnimation(AnimationUtils.loadAnimation(context, R.anim.slide_in_from_right))

But only the later animation is showing?

1 Answers

The only thing I can think of is that notifyDataSetChanged() is quite destructive, it is probably getting called before your animation can get started.

My advice is to delay

adapter.list = list
rv.notifyDataSetChanged()
rv.startAnimation(AnimationUtils.loadAnimation(context, R.anim.slide_in_from_right))

until

rv.startAnimation(AnimationUtils.loadAnimation(context,R.anim.slide_out_to_left))

has sufficient time to run. Here is a link to a previous answer that shows how to setup a onAnimationFinished listener, which should listen for the first animation to finish. Detect animation finish in Android's RecyclerView

Animation animation = AnimationUtils.loadAnimation(getContext(),R.anim.slide_out_to_left);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) { }
            @Override
            public void onAnimationEnd(Animation animation) {
              adapter.list = list;
              adapter.notifyDataSetChanged();
              rv.startAnimation(AnimationUtils.loadAnimation(context, R.anim.slide_in_from_right));
            }
            @Override
            public void onAnimationRepeat(Animation animation) {}
        });
rv.startAnimation(animation));
Related