Android RecyclerView如何仅对项目设置一次动画?

时间:2019-04-25 10:52:32

标签: android android-recyclerview android-animation recycler-adapter listitem

我有一个RecyclerViewAdapter,当它们第一次出现在屏幕上时(例如,向下滚动时),我需要使它们动画化,但是第一次出现时,只有一次,之后每当用户向上滚动时,都不应对此进行动画处理”不能是任何动画。

除了最后一项,我的代码现在可以正常运行,当我向下滚动它时,它总是一遍又一遍地动画。

private Integer lastPosition = -1;

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {

    holder.setIsRecyclable(false);

    // Animations
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition) {
        holder.mImage.setAnimation(AnimationUtils.loadAnimation(context, R.anim.first_animation));
        holder.mView.setAnimation(AnimationUtils.loadAnimation(context, R.anim.second_animation));

        lastPosition = position -1;
    }
}

如果我设置了lastPosition = position;,我只会使加载的前几个项目(根据屏幕大小可见)具有动画效果,而当我向下滚动时,它们则不会获得动画效果。

为什么会这样?正如这里找到的所有示例一样,它们都是首次使用滚动使它们动起来的动画

lastPosition = position;

但是我的失败了吗?

如果这对问题很重要,我的RecyclerAdapter可过滤(implements Filterable)。

2 个答案:

答案 0 :(得分:0)

您可以在列表项中添加其他属性,并检查何时设置动画以及何时不设置动画:

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {

    //Checking if has already animated
    if (!list.get(position).hasAnimated()) {

        //Mark this ViewHolder as animated
        list.get(position).setHasAnimated();
        holder.mImage.setAnimation(AnimationUtils.loadAnimation(context, R.anim.first_animation));
        holder.mView.setAnimation(AnimationUtils.loadAnimation(context, R.anim.second_animation));
    }
}

答案 1 :(得分:-1)

这是一种解决方法,可以在您的 RecyclerViewAdapter 类中使用

ArrayList<Boolean> hasAnimation;

public RecyclerViewAdapter(Context context) {
    hasAnimation=new ArrayList<>();
    this.context=context;
}

然后使用 onBindViewHolder 方法

 @Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {

    hasAnimation.add(true);

    if (hasAnimation.get(position)){
        Animation animation1= AnimationUtils.loadAnimation(context, R.anim.first_animation);
        Animation animation2= AnimationUtils.loadAnimation(context, R.anim.second_animation);
        animation1.setDuration(1000);
        animation2.setDuration(1000);
        holder.mImage.startAnimation(animation1);
        holder.mView.startAnimation(animation2);
        hasAnimation.set(position,false);
    }}

而且可以肯定的是,您可以使用动画部分中的代码简化流程

    holder.mImage.setAnimation(AnimationUtils.loadAnimation(context, R.anim.first_animation));
    holder.mView.setAnimation(AnimationUtils.loadAnimation(context, R.anim.second_animation));

希望有帮助

相关问题