Is there a better way of getting a reference to the parent RecyclerView from the adapter?

寵の児 提交于 2020-07-31 06:47:08

问题


I have a use case where I need a reference to the parent RecyclerView from inside the adapter, specifically inside the onBindViewHolder method. So far what I am doing is assigning it to a private class member in the onCreateViewHolder method passing along the viewGroup parent arg like so:

private ViewGroup mParent;

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

And referencing the parent RecyclerView in onBindViewHolder like this:

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

Is there a better way of doing this? Maybe RecyclerView.Adapter has a way that I may have missed?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/31248529/is-there-a-better-way-of-getting-a-reference-to-the-parent-recyclerview-from-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!