Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 600
nabir Avatar asked Jul 06 '15 14:07

nabir


People also ask

Should I pass context to adapter?

there is nothing wrong with passing context to your adapter. You just should keep your adapter responsible for work with views, leaving networking or database operations for your fragment.


1 Answers

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....     } 
like image 173
NameSpace Avatar answered Oct 15 '22 13:10

NameSpace