How to get a context in a recycler view adapter

后端 未结 12 1285
一向
一向 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条回答
  • 2020-12-02 06:52

    You can use like this view.getContext()

    Example

    holder.tv_room_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                Toast.makeText(v.getContext(), "", Toast.LENGTH_SHORT).show();
    
    
            }
        });
    
    0 讨论(0)
  • 2020-12-02 06:53

    you can use this:

    itemView.getContext()
    
    0 讨论(0)
  • 2020-12-02 06:56

    If you are using Databinding on layout you can get the context from holder. An exemple below.

    @Override
    public void onBindViewHolder(@NonNull GenericViewHolder holder, int position) {
        View currentView = holder.binding.getRoot().findViewById(R.id.cycle_count_manage_location_line_layout);// id of your root layout
        currentView.setBackgroundColor(ContextCompat.getColor(holder.binding.getRoot().getContext(), R.color.light_green));
    }
    
    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-12-02 06:59
    View mView;
    mView.getContext();
    
    0 讨论(0)
  • 2020-12-02 07:00

    Create a constructor of FeedAdapter :

    Context context; //global
    public FeedAdapter(Context context)
    {
       this.context = context;  
    }
    

    and in Activity

    FeedAdapter obj = new FeedAdapter(this);
    
    0 讨论(0)
提交回复
热议问题