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

Android中如何通过Retrofit响应在RecyclerView中展示图片?

解决Retrofit+RecyclerView加载图片的问题

1. Products实体类的图片字段处理

你的Products类中image字段为String类型(对应图片URL),无需手动调用setImage()方法。Retrofit配合Gson转换器接收接口返回的JSON数据时,会自动将对应字段的URL值赋值给image属性,只需保证实体类字段名与接口返回的JSON字段名一致即可(若字段名不匹配,可使用@SerializedName注解做映射)。

示例实体类代码:

public class Products {
    private String image; // 与接口返回JSON中的图片URL字段名保持一致
    // 其他业务字段...

    // Getter方法
    public String getImage() {
        return image;
    }

    // 无需手动编写setImage(),Gson会自动完成赋值
}

2. RecyclerView适配器中加载图片

在onBindViewHolder方法里,不要调用products.setImage(),而是通过products.getImage()获取图片URL,借助Glide或Picasso等图片加载库,将图片加载到对应ImageView中。

基于Glide的实现示例

先添加Glide依赖(Gradle):

dependencies {
    implementation 'com.github.bumptech.glide:glide:4.16.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0'
}

适配器中onBindViewHolder的代码:

@Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
    Products product = productList.get(position);
    String imageUrl = product.getImage();
    
    Glide.with(holder.itemView.getContext())
         .load(imageUrl)
         .placeholder(R.drawable.loading_placeholder) // 加载中占位图
         .error(R.drawable.load_error) // 加载失败占位图
         .into(holder.productImageView);
}

基于Picasso的实现示例

先添加Picasso依赖(Gradle):

dependencies {
    implementation 'com.squareup.picasso:picasso:2.71828'
}

适配器中onBindViewHolder的代码:

@Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
    Products product = productList.get(position);
    String imageUrl = product.getImage();
    
    Picasso.get()
           .load(imageUrl)
           .placeholder(R.drawable.loading_placeholder)
           .error(R.drawable.load_error)
           .into(holder.productImageView);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:55:19