问题
I'm using the new RecyclerView to replace my existing ListViews and ran into the following problem: in the old BaseAdapter, I could create a "fly-in" Animation for each item inside the adapter by simply applying this Animation to the convertView and noticing in a SparseBooleanArray for which position the Animation was already shown.
The onBindViewHolder() method which has replaced getView() doesn't provide access to any Views, nor does the new ItemAnimator. Basically I would need to access the root View of my ViewHolder to apply my own Animation to each item.
Any ideas how to do it?
回答1:
Every view holder used by the RecyclerView has to subclass RecyclerView.ViewHolder and this class has a public field called itemView which contains the View associated with the ViewHolder.
final View view = viewHolder.itemView;
But just in general: Animations work differently in the RecyclerView. Essentially you implement them in a separate class called ItemAnimator:
mRecyclerView.setItemAnimator(new RecyclerView.ItemAnimator() {
@Override
public void runPendingAnimations() {
}
@Override
public boolean animateRemove(RecyclerView.ViewHolder viewHolder) {
return false;
}
@Override
public boolean animateAdd(RecyclerView.ViewHolder viewHolder) {
return false;
}
@Override
public boolean animateMove(RecyclerView.ViewHolder viewHolder, int i, int i2, int i3, int i4) {
return false;
}
@Override
public boolean animateChange(RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder viewHolder2, int i, int i2, int i3, int i4) {
return false;
}
@Override
public void endAnimation(RecyclerView.ViewHolder viewHolder) {
}
@Override
public void endAnimations() {
}
@Override
public boolean isRunning() {
return false;
}
});
In all those callbacks you can access the View instance through the public field as I explained above. The RecyclerView.Adapter unlike the previous Adapters is really just responsible for the data in the RecyclerView.
You can also look at this library on GitHub which already implements a few different ItemAnimators.
Please see the documentation for more information!
来源:https://stackoverflow.com/questions/27206593/recyclerview-how-can-i-get-a-reference-to-each-rows-view