编辑:
This class defines the animations that take place on items as changes are made to the adapter.
因此,除非你逐个添加您的项目到您的RecyclerView并刷新视图在每次迭代,我不认为ItemAnimator是您的需要的解决方案。
以下是如何使用CustomAdapter在RecyclerView项目出现时对其进行动画处理:
public class CustomAdapter extends RecyclerView.Adapter
{
private Context context;
// The items to display in your RecyclerView
private ArrayList items;
// Allows to remember the last item shown on screen
private int lastPosition = -1;
public static class ViewHolder extends RecyclerView.ViewHolder
{
TextView text;
// You need to retrieve the container (ie the root ViewGroup from your custom_item_layout)
// It's the view that will be animated
FrameLayout container;
public ViewHolder(View itemView)
{
super(itemView);
container = (FrameLayout) itemView.findViewById(R.id.item_layout_container);
text = (TextView) itemView.findViewById(R.id.item_layout_text);
}
}
public CustomAdapter(ArrayList items, Context context)
{
this.items = items;
this.context = context;
}
@Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_item_layout, parent, false);
return new ViewHolder(v);
}
@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.itemView, 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.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
}
你的custom_item_layout看起来像这样:
android:id="@+id/item_layout_container"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:id="@+id/item_layout_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
有关CustomAdapters和RecyclerView的详细信息,请参阅此training on the official documentation。
快速滚动问题
使用此方法可能会导致快速滚动的问题。视图可以在动画发生时重复使用。为了避免推荐在分离时清除动画。
@Override
public void onViewDetachedFromWindow(final RecyclerView.ViewHolder holder)
{
((CustomViewHolder)holder).clearAnimation();
}
在CustomViewHolder上:
public void clearAnimation()
{
mRootLayout.clearAnimation();
}
老答案:
看看Gabriele Mariotti’s repo,我相信你会找到你所需要的。他为RecyclerView提供了简单的ItemAnimators,例如SlideInItemAnimator或SlideScaleItemAnimator。