RecyclerView - how can I get a reference to each row's View

空扰寡人 提交于 2019-12-06 11:10:53

问题


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

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