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

RecyclerView绑定Adapter与LayoutManager仍报“No adapter attached”错误求助

解决RecyclerView "No adapter attached; skipping layout" 无列表项显示问题

1. 修复Adapter核心方法缺失

你的GalerieAdapter缺少必须重写的getItemCount()方法——RecyclerView通过该方法判断列表项数量,默认返回0时会直接跳过布局渲染,触发你看到的警告且不显示任何内容。同时onBindViewHolder方法也需要补全,用于绑定数据到Item视图。

补全Adapter核心代码:

class GalerieAdapter(ctx: Activity, items: List<File>) : RecyclerView.Adapter<GalerieAdapter.ViewHolder>() {
    var ctx: Context = ctx
    var items: List<File> = items
    var esVideo = false

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.gallery_item, parent, false)
        return ViewHolder(view)
    }

    // 必须重写:返回列表项总数
    override fun getItemCount(): Int {
        return items.size
    }

    // 必须重写:绑定数据到Item布局控件
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val targetFile = items[position]
        // 根据你的gallery_item布局,完成数据绑定逻辑
        // 示例:判断是否为视频、加载缩略图等
        esVideo = targetFile.extension.equals("mp4", ignoreCase = true) 
                || targetFile.extension.equals("mov", ignoreCase = true)
        // holder.thumbnail.setImageURI(Uri.fromFile(targetFile))
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // 声明Item布局中的控件,比如缩略图、视频标签等
        // val thumbnail: ImageView = itemView.findViewById(R.id.iv_thumbnail)
    }
}

2. 确认数据加载时机与更新逻辑

如果FileUtils.filesInGaleryFolder是异步加载(比如读取本地存储、ContentResolver查询),onCreate初始化Adapter时fileList可能为空。需要给Adapter添加数据更新方法,确保数据加载完成后通知RecyclerView刷新:

  • 在Adapter中添加更新方法:
fun updateFileList(newFiles: List<File>) {
    items = newFiles
    notifyDataSetChanged()
}
  • 数据加载完成后调用该方法(以协程为例):
// 异步加载文件列表
CoroutineScope(Dispatchers.Main).launch {
    val loadedFiles = FileUtils.getGalleryFiles() // 替换为你的实际异步加载方法
    itemAdapter.updateFileList(loadedFiles)
}

3. 检查RecyclerView布局参数

确保Activity布局中RecyclerView的宽高设置正确,避免因wrap_content导致初始无数据时布局高度为0:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerGallery"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    <!-- 其他属性 -->
/>

4. 验证数据源有效性

初始化Adapter前打印文件数量,确认数据源确实有数据:

fileList = FileUtils.filesInGaleryFolder
Log.d("GalleryDebug", "已加载文件数量:${fileList.size}")
itemAdapter = GalerieAdapter(this, fileList)

如果日志显示数量为0,需排查文件读取权限、文件夹路径是否正确等问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:40:21