How to get a context in a recycler view adapter

后端 未结 12 1284
一向
一向 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:39

    You can add global variable:

    private Context context;
    

    then assign the context from here:

    @Override
    public FeedAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
        // create a new view
        View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.feedholder, parent, false);
        // set the view's size, margins, paddings and layout parameters
        ViewHolder vh = new ViewHolder(v);
        // set the Context here 
        context = parent.getContext();
        return vh;
    }
    

    Happy Codding :)

    0 讨论(0)
  • 2020-12-02 06:39

    You can define:

    Context ctx; 
    

    And on onCreate initialise ctx to:

    ctx=parent.getContext(); 
    

    Note: Parent is a ViewGroup.

    0 讨论(0)
  • 2020-12-02 06:46

    First add a global variable

    Context mContext;
    

    Then change your constructor to this

    public FeedAdapter(Context context, List<Post> myDataset) {
        mContext = context;
        mDataset = myDataset;
    }
    

    The pass your context when creating the adapter.

    FeedAdapter myAdapter = new FeedAdapter(this,myDataset);
    
    0 讨论(0)
  • 2020-12-02 06:48

    First globally declare

    Context mContext;

    pass context with the constructor, by modifying it.

    public FeedAdapter(List<Post> myDataset, Context context) {
        mDataset = myDataset;
        this.mContext = context;
    }
    

    then use the mContext whereever you need it

    0 讨论(0)
  • 2020-12-02 06:49

    You have a few options here:

    1. Pass Context as an argument to FeedAdapter and keep it as class field
    2. Use dependency injection to inject Context when you need it. I strongly suggest reading about it. There is a great tool for that -- Dagger by Square
    3. Get it from any View object. In your case this might work for you:

      holder.pub_image.getContext()

      As pub_image is a ImageView.

    0 讨论(0)
  • 2020-12-02 06:51

    You can use pub_image context (holder.pub_image.getContext()) :

    @Override
    public void onBindViewHolder(ViewHolder ViewHolder, int position) {
    
        holder.txtHeader.setText(mDataset.get(position).getPost_text());
    
        Picasso.with(holder.pub_image.getContext()).load("http://i.imgur.com/DvpvklR.png").into(holder.pub_image);
    
    
    }
    
    0 讨论(0)
提交回复
热议问题