我在我需要从适配器内部到父RecyclerView
的参考,特别是onBindViewHolder
方法内的使用情况。到目前为止,我所要做的是将其分配给沿onCreateViewHolder
ARG通过像这样的viewGroup parent
方法私有类成员:
private ViewGroup mParent;
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// inflater logic.
mParent = parent;
}
并引用在这样RecyclerView
父onBindViewHolder
:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// binder logic.
((RecyclerView)mParent).blahBlahBlah();
}
是否有这样做的更好的办法?也许RecyclerView.Adapter
有,我可能已经错过了呢?
实际上,有以该重视的适配器RecyclerView
callsback的具体方法。只是重写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....
}
另一种方式是在构造函数传递一个参考,例如
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) {
...
}
}