Android RecyclerView:如何创建插入动画效果?

Android RecyclerView:如何创建插入动画效果?,android,animation,delay,android-recyclerview,Android,Animation,Delay,Android Recyclerview,我有一个ReyclerView与LinearLayoutManager和一个适配器一起工作。我有一个项目列表,我想显示在带有插入(滑入)动画的recyclerview中。我该怎么办 我想根据项目的索引以线性增加的延迟显示动画 目前,如果我使用两个按钮“添加”和“删除”,然后在recyclerview上执行相应的操作(notifyItemInserted()和notifyItemRemoved()),动画效果会很好 如果我以编程方式循环数据集并添加项目,再次使用notifyItemInserted

我有一个
ReyclerView
LinearLayoutManager
和一个
适配器一起工作。我有一个项目列表,我想显示在带有插入(滑入)动画的recyclerview中。我该怎么办

我想根据项目的索引以线性增加的延迟显示动画

目前,如果我使用两个按钮“添加”和“删除”,然后在recyclerview上执行相应的操作(
notifyItemInserted()
notifyItemRemoved()
),动画效果会很好

如果我以编程方式循环数据集并添加项目,再次使用
notifyItemInserted()
,我看不到任何动画。我只看到所有项目几乎同时出现

如果我使用带有线性延迟的Asynctasks,然后在
OnPostExecute()
中添加/删除该项,我仍然看不到任何动画。此外,如果多个插入线程等待所有删除线程完成(没有位置让删除线程运行),我还看到可能会出现死锁

我做错了什么


我已经完成了与此相关的大部分问题,并花了几天时间在recyclerview的动画部分进行了探索,但仍然不走运。

下面是我如何在我的
适配器中添加动画。
。这将使推送效果产生动画效果,行从右侧进入

首先用xml定义动画(
res/anim/push_left_in.xml

此动画将在每次添加新行时显示,它应该适用于您的情况

编辑

这就是如何使用
RecyclerView

@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
    holder.text.setText(items.get(position));

    // Here you apply the animation when the view is bound
    setAnimation(holder.container, position);
}

/**
 * Here is the key method to apply the animation
 */
private void setAnimation(View viewToAnimate, int position)
{
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition)
    {
        Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.push_left_in);
        viewToAnimate.startAnimation(animation);
        lastPosition = position;
    }
}
这对我很有用:

animation.setStartOffset(position*100);

将此行添加到您的RecyclerView xml中:


android:animateLayoutChanges=“true”

看一看。作者解释了当你使用
RecyclerView
@milindbableshwarI已经编辑了我答案的相关代码,请看一看。@milindbableshwarpet!这很有效。接下来的问题是,如何为项目删除设置动画?我的意思是,如果我要以编程方式删除l物品列表,我应该从哪里开始删除物品动画?不幸的是,我不知道。我做了一些研究,但找不到任何相关的答案。我认为可以创建一个新的问题来解决这个问题。@milindbableshwarhow是否初始化或定义了lastPosition?我假设它是(位置-1)定义为一个方法变量。您能详细说明一下吗?@Hmm我很高兴它能帮上忙!只有当您不在recycler视图(notifyItemChange、notifyItemRemove等)中进行更改时,才可以使用此参数。这通常会破坏RecyclerViews,另请参阅
@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
    holder.text.setText(items.get(position));

    // Here you apply the animation when the view is bound
    setAnimation(holder.container, position);
}

/**
 * Here is the key method to apply the animation
 */
private void setAnimation(View viewToAnimate, int position)
{
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition)
    {
        Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.push_left_in);
        viewToAnimate.startAnimation(animation);
        lastPosition = position;
    }
}
animation.setStartOffset(position*100);