You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中onBindViewHolder时如何获取图片?Picasso上下文该用什么?

问题:Picasso加载图片时需传入的Context是什么?

我有一个用于展示用户名、用户头像与消息内容的聊天消息视图,我的MessageAdapter类中的onBindViewHolder方法代码如下:

public void onBindViewHolder(final MessageViewHolder holder, int position) {
 auth = FirebaseAuth.getInstance();
 String currenUserId = auth.getCurrentUser().getUid();
 Message c = mMessageList.get(position);
 String fromUser = c.getFrom();
 reference = FirebaseDatabase.getInstance().getReference().child("Users");
 reference.child(fromUser).addValueEventListener(new ValueEventListener() {
 @Override
 public void onDataChange(DataSnapshot dataSnapshot) {
 String name = dataSnapshot.child("name").getValue().toString();
 String image = dataSnapshot.child("image").getValue().toString();
 holder.messageName.setText(name);
 if(!image.equals("default")) {
 Picasso.with().load(image).placeholder(R.drawable.avatar).into(holder.messageProfile);
 }
 }
 @Override
 public void onCancelled(DatabaseError databaseError) {
 }
 });
 holder.messageText.setText(c.getMessage());
 Calendar calendar = Calendar.getInstance();
 calendar.setTimeInMillis(c.getTime());
 int mHour = calendar.get(Calendar.HOUR_OF_DAY);
 int mMin = calendar.get(Calendar.MINUTE);
 holder.messageTime.setText(mHour+":"+mMin);
}

我使用Picasso加载图片,请问Picasso.with()应当传入什么作为Context?


回答

嘿,这个问题挺常见的!你可以直接传入ViewHolder里ImageView的Context,也就是holder.messageProfile.getContext()。因为ImageView本身就持有它所在页面的上下文引用,这样做既安全,还能避免潜在的内存泄漏问题。

修改后的Picasso调用代码如下:

if(!image.equals("default")) {
 Picasso.with(holder.messageProfile.getContext())
        .load(image)
        .placeholder(R.drawable.avatar)
        .into(holder.messageProfile);
}

顺便给你两个小优化建议:

  • 别在onBindViewHolder里重复初始化FirebaseAuth和DatabaseReference,把它们移到Adapter的构造方法里只创建一次,能有效提升列表滚动的性能。
  • 记得在Adapter销毁的时候移除ValueEventListener,不然会一直保留监听,可能造成不必要的资源消耗和内存泄漏哦。

内容的提问来源于stack exchange,提问作者Hemal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:52:59