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

嵌套RecyclerView中使用Glide加载图片报错:无法访问Fragment

问题

我想在嵌套RecyclerView的ImageView中,通过Glide库从URL加载图片,相关代码如下:

@Override
public void onBindViewHolder(@NonNull InnerAdapter.ViewHolder holder, int position) {
    holder.textView.setText(movieList.get(position).getName());

    Glide.with(context).load("https://image.tmdb.org/t/p/w500" + movieList.get(position).getImage()).into(holder.imageView);
}

我通过RecyclerView传递Activity上下文,但运行应用时出现如下错误:

error: cannot access Fragment

Glide.with(context).load("https://image.tmdb.org/t/p/w500" + movieList.get(position).getImage()).into(holder.imageView);

class file for android.support.v4.app.Fragment not found

解决方法

这个错误是因为Glide依赖Android Support库的v4 Fragment类,但项目缺少对应依赖或版本不匹配,可按以下方式修复:

  • 添加v4支持库依赖
    若项目仍使用旧Support库,在模块级build.gradle的dependencies块中添加(版本号需与项目其他Support库保持一致):

    implementation 'com.android.support:support-v4:28.0.0'
    
  • 迁移到AndroidX(推荐)
    若项目已迁移到AndroidX,确保Glide使用适配AndroidX的版本,并检查依赖完整性:

    1. 引入适配AndroidX的Glide版本:
      implementation 'com.github.bumptech.glide:glide:4.16.0'
      annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0'
      
    2. 确认项目包含AndroidX核心依赖:
      implementation 'androidx.appcompat:appcompat:1.6.1'
      implementation 'androidx.core:core-ktx:1.12.0'
      
  • 替换Glide的上下文参数
    无需传递Activity上下文,直接使用View的上下文可规避依赖问题,修改代码为:

    Glide.with(holder.imageView.getContext())
         .load("https://image.tmdb.org/t/p/w500" + movieList.get(position).getImage())
         .into(holder.imageView);
    

内容的提问来源于stack exchange,提问作者Malte Möhring

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:04:07