要实现Android RecyclerView仅对项进行一次动画,可以使用ItemAnimator来控制动画的播放。下面是一个解决方法的代码示例:
首先,创建一个自定义的ItemAnimator,继承自默认的DefaultItemAnimator,并重写animateChange()方法:
public class OnlyOnceItemAnimator extends DefaultItemAnimator {
private HashSet mAnimatedItems = new HashSet<>();
@Override
public boolean animateChange(RecyclerView.ViewHolder oldHolder, RecyclerView.ViewHolder newHolder, int fromX, int fromY, int toX, int toY) {
if (!mAnimatedItems.contains(oldHolder)) {
mAnimatedItems.add(oldHolder);
return super.animateChange(oldHolder, newHolder, fromX, fromY, toX, toY);
}
dispatchChangeFinished(oldHolder, true);
return false;
}
@Override
public void runPendingAnimations() {
super.runPendingAnimations();
mAnimatedItems.clear();
}
@Override
public void endAnimation(RecyclerView.ViewHolder item) {
super.endAnimation(item);
mAnimatedItems.remove(item);
}
@Override
public void endAnimations() {
super.endAnimations();
mAnimatedItems.clear();
}
}
然后,在RecyclerView初始化时,设置自定义的ItemAnimator:
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setItemAnimator(new OnlyOnceItemAnimator());
这样,每次只有第一次出现的项会执行动画,后续出现的项将不再执行动画。