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

Kotlin中RecyclerView适配器内声明双ViewHolder内部类报错求解

解决Kotlin RecyclerView.Adapter内部ViewHolder类的"Expecting member declaration"错误

你在ChatAdapter中声明SentMessageViewHolder和ReceivedMessageViewHolder时出现的报错,翻译为:

期望成员声明

错误原因

问题出在ViewHolder类的次级构造函数写法上:

  1. Kotlin中声明次级构造函数必须显式使用constructor关键字,你直接写函数名的写法不符合语法规范
  2. 次级构造函数必须调用类的主构造函数(或其他次级构造函数),而你的次级构造函数没有调用继承自RecyclerView.ViewHolder的主构造(该构造要求传入View类型参数)

修改方案

给次级构造函数添加constructor关键字,并且在次级构造函数中通过this(binding.root)调用主构造函数(Binding对象的root属性就是对应的item布局View)

修改后的代码

class ChatAdapter(private val dataSet: ArrayList<ChatMessage>, private val receiverProfilImage: Bitmap, val senderId: String) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    class SentMessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        lateinit var binding: ItemContainerSentMessageBinding

        // 添加constructor关键字,同时调用主构造函数
        constructor(binding: ItemContainerSentMessageBinding) : this(binding.root) {
            this.binding = binding
        }

        fun setData(chatMessage: ChatMessage) {
            binding.textMessage.text = chatMessage.message
            binding.textDateTime.text = chatMessage.dateTime
        }
    }

    class ReceivedMessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        lateinit var binding: ItemContainerReceivedMessageBinding

        // 添加constructor关键字,同时调用主构造函数
        constructor(binding: ItemContainerReceivedMessageBinding) : this(binding.root) {
            this.binding = binding
        }

        fun setData(chatMessage: ChatMessage, receiverProfilImage: Bitmap) {
            binding.textMessage.text = chatMessage.message
            binding.textDateTime.text = chatMessage.dateTime
            binding.imageProfil.setImageBitmap(receiverProfilImage)
        }
    }

    // 补充Adapter必须实现的方法(如getItemViewType、onCreateViewHolder、onBindViewHolder等)
    // ...
}

更简洁的写法(可选)

你可以直接把Binding作为主构造参数,去掉次级构造函数,更符合Kotlin的简洁风格:

class SentMessageViewHolder(val binding: ItemContainerSentMessageBinding) : RecyclerView.ViewHolder(binding.root) {
    fun setData(chatMessage: ChatMessage) {
        binding.textMessage.text = chatMessage.message
        binding.textDateTime.text = chatMessage.dateTime
    }
}

class ReceivedMessageViewHolder(val binding: ItemContainerReceivedMessageBinding) : RecyclerView.ViewHolder(binding.root) {
    fun setData(chatMessage: ChatMessage, receiverProfilImage: Bitmap) {
        binding.textMessage.text = chatMessage.message
        binding.textDateTime.text = chatMessage.dateTime
        binding.imageProfil.setImageBitmap(receiverProfilImage)
    }
}

内容的提问来源于stack exchange,提问作者Captai-N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 11:57:32