Search code examples
androidanimationscrollandroid-recyclerview

Android animation stop works in recyclerview when view go off the screen


I set animaion like this:

@Override
    public void onBindViewHolder(ViewHolder holder, int position) {     
            Animation anim = AnimationUtils.loadAnimation(context, R.anim.rotate);
            holder.windPropellers.setAnimation(anim);
            break;
}

When the view scrolled off the screen animation stops. And when you scroll back it's not animating at all.


Solution

  • You need to set transient state in the view to prevent it from being recycled.

    Your code would look like this:

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {     
            Animation anim = AnimationUtils.loadAnimation(context, R.anim.rotate);
            holder.windPropellers.setHasTransientState(true);
            anim.setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    holder.windPropellers.setHasTransientState(false);
                }
            });
            holder.windPropellers.setAnimation(anim);
            break;
    

    }