如何用Retrofit获取图片链接,结合Picasso与RecyclerView实现图片列表展示
没问题,我来帮你把Retrofit和RecyclerView结合起来实现图片列表展示,咱们一步步拆解来做:
1. 先搞定Retrofit的配置与数据获取
首先确保你的项目里已经添加了必要依赖(如果还没加的话),在Module级别的build.gradle中添加:
// Retrofit核心依赖 implementation 'com.squareup.retrofit2:retrofit:2.9.0' // Gson转换器,用于解析JSON数据 implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // 图片加载用Glide(也可以选Picasso,二选一即可) implementation 'com.github.bumptech.glide:glide:4.15.1' annotationProcessor 'com.github.bumptech.glide:compiler:4.15.1'
接下来创建Retrofit的API接口,定义获取图片列表的请求:
public interface ImageApiService { // 替换成你的实际接口路径,比如"/api/image/list" @GET("你的接口路径") Call<ImageResponse> getImageList(); }
这里的ImageResponse是你的顶层JSON实体类,需要包含List<ResultsPojo>字段;而ResultsPojo里必须有对应图片链接的属性(要和JSON里的key匹配,比如JSON里是"image_url",就给字段加@SerializedName("image_url")注解)。
然后在Activity/Fragment中初始化Retrofit并发起请求:
// 初始化Retrofit实例 Retrofit retrofit = new Retrofit.Builder() .baseUrl("你的API基础地址,比如https://example.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); // 创建API服务实例 ImageApiService apiService = retrofit.create(ImageApiService.class); // 发起异步请求 Call<ImageResponse> call = apiService.getImageList(); call.enqueue(new Callback<ImageResponse>() { @Override public void onResponse(Call<ImageResponse> call, Response<ImageResponse> response) { if (response.isSuccessful() && response.body() != null) { // 获取到图片列表数据 List<ResultsPojo> imageList = response.body().getResultList(); // 把数据传给适配器 listAdapter.updateData(imageList); // 通知适配器刷新UI listAdapter.notifyDataSetChanged(); } } @Override public void onFailure(Call<ImageResponse> call, Throwable t) { // 处理请求失败的情况,比如弹出提示 Toast.makeText(MainActivity.this, "获取数据失败:" + t.getMessage(), Toast.LENGTH_SHORT).show(); } });
2. 完善你的RecyclerView适配器
基于你给出的适配器开头,咱们补全所有必要逻辑:
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ListViewHolder> { private List<ResultsPojo> resultList; private LayoutInflater layoutInflater; // 构造方法,传入上下文和初始数据 public ListAdapter(Context context, List<ResultsPojo> resultList) { this.layoutInflater = LayoutInflater.from(context); this.resultList = resultList != null ? resultList : new ArrayList<>(); } // 提供更新数据的方法,方便后续从Retrofit回调中调用 public void updateData(List<ResultsPojo> newList) { this.resultList.clear(); this.resultList.addAll(newList); } @NonNull @Override public ListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // 加载列表项布局(替换成你自己的item布局,比如R.layout.item_image) View itemView = layoutInflater.inflate(R.layout.item_image, parent, false); return new ListViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull ListViewHolder holder, int position) { ResultsPojo currentItem = resultList.get(position); // 用Glide加载图片到ImageView Glide.with(holder.itemView.getContext()) .load(currentItem.getImageUrl()) // 替换成你ResultsPojo里的图片链接getter方法 .placeholder(R.drawable.placeholder) // 加载中的占位图 .error(R.drawable.error_img) // 加载失败的占位图 .into(holder.imageView); } @Override public int getItemCount() { return resultList.size(); } // ViewHolder类,绑定列表项控件 public class ListViewHolder extends RecyclerView.ViewHolder { ImageView imageView; public ListViewHolder(@NonNull View itemView) { super(itemView); // 替换成你item布局里ImageView的id imageView = itemView.findViewById(R.id.item_img); } } }
3. 初始化RecyclerView
在你的Activity/Fragment的onCreate方法中,完成RecyclerView的基础配置:
RecyclerView recyclerView = findViewById(R.id.recycler_view); // 设置布局管理器,这里用线性布局,你也可以换成网格布局 recyclerView.setLayoutManager(new LinearLayoutManager(this)); // 创建适配器实例 listAdapter = new ListAdapter(this, null); // 给RecyclerView设置适配器 recyclerView.setAdapter(listAdapter);
关键注意事项
- 确保
ResultsPojo的字段和JSON数据完全对应,比如JSON里的图片链接字段是"img_url",实体类要这么写:@SerializedName("img_url") private String imageUrl; public String getImageUrl() { return imageUrl; } - 一定要用Glide/Picasso这类图片加载库,它们会自动处理缓存、线程调度、图片压缩,避免OOM问题。
- Retrofit的
enqueue回调默认在主线程执行,所以直接更新适配器是安全的,不用手动切换线程。
内容的提问来源于stack exchange,提问作者Bo Z
相关产品推荐
相关产品推荐

