Android RecyclerView适配器+;数据绑定

Android RecyclerView适配器+;数据绑定,android,kotlin,android-recyclerview,Android,Kotlin,Android Recyclerview,好的,我正在尝试在我的recyclerview适配器中实现数据绑定,我需要帮助,因为我不知道具体如何实现?我正试图从我的recyclerview适配器中删除样板代码,这就是为什么。在下面查看我的代码: 自定义行(回收视图项目布局) MyAdapter(Recyclerview适配器) classmyadapter:RecyclerView.Adapter(){ 类MyViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){ } 重写

好的,我正在尝试在我的recyclerview适配器中实现数据绑定,我需要帮助,因为我不知道具体如何实现?我正试图从我的recyclerview适配器中删除样板代码,这就是为什么。在下面查看我的代码:

自定义行(回收视图项目布局)

MyAdapter(Recyclerview适配器)

classmyadapter:RecyclerView.Adapter(){
类MyViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
}
重写CreateViewHolder(父级:ViewGroup,viewType:Int):MyViewHolder{
val view=LayoutInflater.from(parent.context).充气(R.layout.custom_行,parent,false)
返回MyViewHolder(视图)
}
重写getItemCount():Int{
TODO(“尚未实施”)
}
覆盖onBindViewHolder(holder:MyViewHolder,位置:Int){
TODO(“尚未实施”)
}
}

你就快到了。要完成您的实现,请执行以下操作

在适配器中,创建支持数据绑定的视图保持架

class ViewHolder private constructor(private val binding: CustomRowBinding)
        : RecyclerView.ViewHolder(binding.root) {

        fun bind(todo: ToDoData) {
            binding.todo = toDoData
            // make sure to include this so your view will be updated
            binding.executePendingBindings()
        }

        companion object {
            fun from(parent: ViewGroup): ViewHolder {
                val layoutInflater = LayoutInflater.from(parent.context)
                val binding = CustomRowBinding.inflate(layoutInflater, parent, false)

                return ViewHolder(binding)
            }
        }
    }
在您的oncreateViewHolder中

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder.from(parent)
    }
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val todo = todoList[position] // this will be the list object you created
        holder.bind(todo)
    }
最后是关于BindViewHolder

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder.from(parent)
    }
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val todo = todoList[position] // this will be the list object you created
        holder.bind(todo)
    }

我已删除我的“MyViewHolder”,并将其替换为您提供的。这很有效,谢谢!:)“CustomRowBinding”类是如何生成的?请解释我正在尝试,但找不到用于recycleView的绑定类。
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val todo = todoList[position] // this will be the list object you created
        holder.bind(todo)
    }