有没有更好的方法从适配器获取对父回收视图的引用?

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

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有一个方法,我可能已经错过了?

34260 次浏览

Another way is passing a reference in the constructor, e.g.

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

There's actually a specific method that callsback with the RecyclerView that attaches to the adapter. Just override the onAttachedToRecylerView(RecyclerView recyclerView) method.

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