Is there a better way of getting a reference to the parent RecyclerView from the adapter?
Solution 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....
}
Solution 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) {
...
}
}