有没有更好的方法来从适配器获取对父RecyclerView的引用?


79

我有一个用例,需要RecyclerView从适配器内部(特别是在onBindViewHolder方法内部)对父级进行引用。到目前为止,我正在做的就是将它分配给argonCreateViewHolder传递的方法中的私有类成员,viewGroup parent如下所示:

private ViewGroup mParent;

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // inflater logic.
    mParent = parent;
}

并引用父RecyclerViewonBindViewHolder这样的:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // binder logic.
    ((RecyclerView)mParent).blahBlahBlah();
}

有更好的方法吗?也许RecyclerView.Adapter有一种我可能错过的方式?

Answers:


216

实际上,有一个特定的方法可以通过RecyclerView附加到适配器的回调。只是重写onAttachedToRecylerView(RecyclerView recyclerView)方法。

public class Adapter_RV extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    RecyclerView mRecyclerView; 


    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);

        mRecyclerView = recyclerView;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        mRecyclerView....
    }

1
我怎么在文档中错过了这个!谢谢,这正是我想要的!
nabir 2015年

5
该文档说:“请记住,多个RecyclerView可能会观察到同一适配器。” developer.android.com/reference/android/support/v7/widget / ... 如果我错了,请纠正我,但是如果将适配器分配给多个RecyclerView,这不会造成问题吗?
UnTraDe

3
@UnTraDe是的。上面的代码将覆盖以前的RecyclerView实例。一种解决方案是维护一个附加的RecyclerView实例的列表,并删除onDetachedFromRecyclerView(..)中的实例。如果可能,最好避免这种情况,只为每个RecyclerView实例创建一个适配器实例。
masterwok

值得第200喜欢!
iuq

3

另一种方法是在构造函数中传递引用,例如

public final class MyAdapter extends RecyclerView.Adapper {
    private final recyclerView;

    public MyAdapter(@NonNull RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
    }

    ...

    @Override
     public void onBindViewHolder(ViewHolder holder, int position) {
        ...
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.