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

mil*_*war 8 animation android delay android-recyclerview

ReyclerView和a LinearLayoutManager和a 一起工作Adapter<ViewHolder>.我有一个项目列表,我想在recyclelerview中显示插入(幻灯片放入)动画.我该怎么做?

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

目前,如果我使用2个按钮,'添加'和'删除',然后在recyclerview上执行相应的操作(notifyItemInserted()并且notifyItemRemoved(),动画很好地进行.

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

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

我究竟做错了什么 ?

我已经在SO上经历了与此相关的大部分问题,并且花了几天时间围绕着Recyclerview的动画部分,仍然没有运气.

Mar*_*cus 9

以下是我在我的动画中添加动画的方法Adapter.这将使推动效果生动,行从右侧进入.

首先在xml(res/anim/push_left_in.xml)中定义动画

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%p" android:toXDelta="0"
        android:duration="300"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
        android:duration="300" />
</set>
Run Code Online (Sandbox Code Playgroud)

然后将其设置在适配器中

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row;
    if (convertView == null) {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        row = inflater.inflate(R.layout.music_list_item, null);
    } else {
        row = convertView;
    }

    ...

    //Load the animation from the xml file and set it to the row
    Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.push_left_in);
    animation.setDuration(500);
    row.startAnimation(animation);

    return row;
}
Run Code Online (Sandbox Code Playgroud)

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

编辑

这是你可以使用a添加动画的方法 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;
    }
}
Run Code Online (Sandbox Code Playgroud)


pen*_*Dev 5

将此行添加到RecyclerView xml:

android:animateLayoutChanges="true"