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

时间:2015-07-06 14:30:22

标签: android android-adapter android-recyclerview

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

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有一种我可能错过的方式?

2 个答案:

答案 0 :(得分:155)

实际上有一种特定的方法可以使用附加到适配器的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 :(得分: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) {
        ...
    }
}