RecyclerView : How to create insert animation effect?

徘徊边缘 提交于 2019-11-30 07:24:09

Below is how I add an animation in my Adapter. This will animate a push effect, with the row coming in from the right.

First define the animation in 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>

Then set it in your Adapter as so

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

This animation will be displayed each time you add a new row, it should work in your case.

Edit

This is how you could add an animation using 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;
    }
}

Add this line to your RecyclerView xml:

android:animateLayoutChanges="true"

user2852741

This works for me:

animation.setStartOffset(position*100);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!