How to get a context in a recycler view adapter

后端 未结 12 1399
一向
一向 2020-12-02 06:12

I\'m trying to use picasso library to be able to load url to imageView, but I\'m not able to get the context to use the picasso library correctly.



        
12条回答
  •  -上瘾入骨i
    2020-12-02 06:59

    Short answer:

    Context context;
    
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        context = recyclerView.getContext();
    }
    

    Explanation why other answers are not great:

    1. Passing Context to the adapter is completely unnecessary, since RecyclerView you can access it from inside the class
    2. Obtaining Context at ViewHolder level means that you do it every time you bind or create a ViewHolder. You duplicate operations.
    3. I don't think you need to worry about any memory leak. If your adapter lingers outside your Activity lifespan (which would be weird) then you already have a leak.

提交回复
热议问题