You need to enable JavaScript to run this app. 安卓开发:如何在RecyclerView集成Picasso加载SQLite存储的车辆图片
优惠活动
大模型
产品
解决方案
定价
更多

安卓开发:如何在RecyclerView集成Picasso加载SQLite存储的车辆图片

RecyclerView列表集成Picasso加载二手车网络图片实现方案

前置校验

  • 确认Products实体类已存储爬取的图片链接字段,提供getImageUrl()方法获取对应车辆的图片地址
  • 已在模块级build.gradle的dependencies块中添加Picasso依赖:implementation 'com.squareup.picasso:picasso:2.8'
  • 已在AndroidManifest.xml中添加网络权限:<uses-permission android:name="android.permission.INTERNET" />

核心代码修改

你已完成ViewHolder初始化、文本绑定的基础逻辑,仅需在onBindViewHolder方法中补充图片加载逻辑,同时处理列表复用时的图片错位、空链接、加载异常场景:

@Override
public void onBindViewHolder(@NonNull SearchViewHolder holder, int position) {
    Products currentItem = products.get(position);
    // 保留原有文本绑定逻辑
    holder.name.setText(currentItem.getName());
    holder.price.setText(currentItem.getPrice());
    holder.year.setText(currentItem.getYear());
    holder.location.setText(currentItem.getLocation());

    // 新增图片加载逻辑
    // 清空复用Holder的旧图片,避免快速滚动时的图片错位
    holder.image.setImageDrawable(null);
    // 处理空图片链接的异常场景
    if (TextUtils.isEmpty(currentItem.getImageUrl())) {
        // 替换为你项目的本地默认车辆占位图资源ID
        holder.image.setImageResource(R.drawable.ic_default_car);
        return;
    }
    // 调用Picasso加载网络图片
    Picasso.get()
        .load(currentItem.getImageUrl()) // 传入SQLite中存储的图片链接
        .placeholder(R.drawable.ic_image_loading) // 加载中显示的本地占位图
        .error(R.drawable.ic_image_load_failed) // 加载失败显示的本地错误图
        .fit() // 自动适配ImageView尺寸,降低内存占用
        .centerCrop() // 裁剪规则,避免图片拉伸变形
        .into(holder.image);
}

关键避坑点

  • 复用场景兼容:提前清空ImageView的原有内容,是RecyclerView适配图片加载库的核心逻辑,否则快速滚动时会出现图片串号的问题
  • 内存优化:fit()方法会自动测量ImageView的尺寸,只加载适配尺寸的图片,避免加载原图导致的OOM崩溃
  • 资源替换:所有占位图、错误图都使用项目本地的资源ID,不需要引用外部链接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 19:36:07