android - 回收站 View : How to create insert animation effect?

标签 android animation delay android-recyclerview

我有一个 ReyclerView使用 LinearLayoutManager和一个 Adapter<ViewHolder> .我有一个项目列表,我想在 recyclerview 中显示插入(滑入)动画。我该怎么做?

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

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

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

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

我做错了什么?

我已经在 SO 上解决了与此相关的大部分问题,并且花了几天时间研究 recyclerview 的动画部分,但仍然没有成功。

最佳答案

下面是我如何在我的 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>

然后在你的Adapter中这样设置

@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;
}

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

编辑

这是使用 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;
    }
}

关于android - 回收站 View : How to create insert animation effect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28986269/

相关文章:

Java 瓦片 map 加载器

android - 带有可点击链接的EditText,除非用户自行更改它,否则不可编辑/Kotlin,Android

java - 无法在 Android 应用程序的对象内返回 JSON 对象

安卓 : Image button or button Highlighted with Effect when Pressed

python - 在 matplotlib 中为旋转的 3D 图形制作动画

圆角半径的Android动画

javascript - 在 mouseenter jquery 中使用延迟

html - 使一段文本出现,另一段在相同的延迟下消失

Android JavaScript 自动完成表单 WebView

jquery - 延迟 jquery 重定向