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

前端 未结 2 1762
傲寒
傲寒 2021-01-31 00:55

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

2条回答
  •  遇见更好的自我
    2021-01-31 01:37

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

提交回复
热议问题