有没有更好的方式从适配器获得对父RecyclerView的引用?

我有一个用例,我需要从适配器内部引用父RecyclerView ,特别是在onBindViewHolder方法中。 到目前为止,我正在做的是将其分配给onCreateViewHolder方法中的私有类成员传递viewGroup parent arg像这样:

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

并像这样在onBindViewHolder引用父RecyclerView

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

有没有更好的方法来做到这一点? 也许RecyclerView.Adapter有一种方法,我可能错过了?

Solutions Collecting From Web of "有没有更好的方式从适配器获得对父RecyclerView的引用?"

实际上有一个特定的方法,callback与附加到适配器的RecyclerView。 只需重写onAttachedToRecylerView()方法。

 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.... } 

可能你想在viewHolder中创build一个接口,并传递给父类并在那里实现。

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

 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) { ... } }