未解决的参考:切换到视图绑定后的 myViewHolder

Unresolved reference: myViewHolder after switching to View Binding

从删除 kotlin_extensions 切换到视图绑定后,我在 onBindViewHolder 方法中收到“未解析的引用:myViewHolder”,当我替换“myViewHolder”时使用“持有人”,然后它会给我一个“未解决的参考:绑定”。我该如何解决这个问题。

我的适配器

class MyAdapter(private val context: Context, private val mHelper : TaskDbHelper) : RecyclerView.Adapter<MyAdapter.MyViewHolder>(),
SwipeAndDragHelper.ActionCompletionContract {
class MyViewHolder(val binding: CellCardsBinding): RecyclerView.ViewHolder(binding.root ) {
    fun binding() {

    }
}
private var touchHelper: ItemTouchHelper? = null
private var list = mutableListOf<MyObject>()

override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
    initList()
    super.onAttachedToRecyclerView(recyclerView)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
   return MyViewHolder(CellCardsBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}

@RequiresApi(Build.VERSION_CODES.P)
@SuppressLint("ClickableViewAccessibility")
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

    val myObject = list[position]

   myViewHolder.bind(myObject)

    val activity: Activity = context as Activity
    
    holder.binding.text.setOnClickListener{
        activity.launchActivity<AddNoteActivity>(42) {
            putExtra("PositionInList", position.toString())
            putExtra("TaskTitle", myObject.title)
            putExtra("TaskText", myObject.text)
        }
    }

    activity.findViewById<RecyclerView>(R.id.recyclerView).setOnTouchListener { _, event ->
        when (event.actionMasked) {
            MotionEvent.ACTION_UP -> {
                updateNotesPositionInDb()
                false
            }

            else -> {
                false
            }
        }
    }

    holder.binding.title.setOnTouchListener { _, event ->
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                touchHelper!!.startDrag(holder)
                false
            }
            else -> {
                false
            }
        }

    }
}

private fun initList() {
    list.clear()
    val db = mHelper.readableDatabase
    val cursor = db.query(
        TaskContract.TaskEntry.TABLE,
        arrayOf(
            TaskContract.TaskEntry.ID,
            TaskContract.TaskEntry.COL_TASK_TITLE,
            TaskContract.TaskEntry.COL_TASK_TEXT,
            TaskContract.TaskEntry.COL_TASK_DATE),null, null, null, null, TaskContract.TaskEntry.ID)
    while (cursor.moveToNext()) {
        val id = cursor.getColumnIndex(TaskContract.TaskEntry.ID)
        val idTitle = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE)
        val idText = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TEXT)
        val idDate = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_DATE)

        list.add(MyObject(cursor.getString(id), cursor.getString(idTitle), cursor.getString(idText), cursor.getString(idDate)))
    }
    notifyDataSetChanged()

    cursor.close()
    db.close()
}

override fun getItemCount(): Int {
    return list.size
}

override fun onViewMoved(oldPosition: Int, newPosition: Int) {
    val target = list[oldPosition]
    list.removeAt(oldPosition)
    list.add(newPosition, target)
    notifyItemMoved(oldPosition, newPosition)
}

override fun onViewSwiped(position: Int) {
    deleteTask(list[position].ID)
    list.removeAt(position)
    notifyItemRemoved(position)
    updateNotesPositionInDb()
}
fun setTouchHelper(touchHelper: ItemTouchHelper) {
    this.touchHelper = touchHelper
}

fun addTask(taskTitle : String, taskText: String) {
    val values = ContentValues()

    val sdf = SimpleDateFormat("dd/MM/yyyy/", Locale.US)
    val date = sdf.format(Date())

    values.put(TaskContract.TaskEntry.ID, list.size)
    values.put(TaskContract.TaskEntry.COL_TASK_TITLE, taskTitle)
    values.put(TaskContract.TaskEntry.COL_TASK_TEXT, taskText)
    values.put(TaskContract.TaskEntry.COL_TASK_DATE, date)

    val db = mHelper.readableDatabase
    db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
        null,
        values,
        SQLiteDatabase.CONFLICT_REPLACE)
    db.close()

    list.add(MyObject(list.size.toString(), taskTitle, taskText, date))

    notifyItemInserted(list.size)
}

fun addTask() {
    val test: Activity = context as Activity
    test.launchActivity<AddNoteActivity>(42) {
        /* putExtra("user", "854")
         p utExtra("user2", "46850") */
    }
}

private fun deleteTask(taskId: String) {

    val db = mHelper.readableDatabase
    db.delete(TaskContract.TaskEntry.TABLE,
        "id=$taskId", null)
    db.close()
}

fun modifyTask(taskPosition: String, taskTitle: String, taskText: String) {
    val target = list[taskPosition.toInt()]

    target.title = taskTitle
    target.text = taskText

    val values = ContentValues()

    val sdf = SimpleDateFormat("dd/MM/yyyy/", Locale.US)
    val date = sdf.format(Date())

    values.put(TaskContract.TaskEntry.ID, taskPosition)
    values.put(TaskContract.TaskEntry.COL_TASK_TITLE, taskTitle)
    values.put(TaskContract.TaskEntry.COL_TASK_TEXT, taskText)
    values.put(TaskContract.TaskEntry.COL_TASK_DATE, date)

    val db = mHelper.readableDatabase
    db.update(TaskContract.TaskEntry.TABLE,
        values, TaskContract.TaskEntry.ID + "=" + target.ID, null)

    db.close()

    notifyItemChanged(taskPosition.toInt())
}

private fun updateNotesPositionInDb() {
    val db = mHelper.readableDatabase

    var i = 0
    while (i < list.size) {
        val values = ContentValues()

        values.put(TaskContract.TaskEntry.ID, i)
        db.update(TaskContract.TaskEntry.TABLE,
            values, TaskContract.TaskEntry.ID + "=? AND " + TaskContract.TaskEntry.COL_TASK_TITLE + "=?", arrayOf(list[i].ID, list[i].title))
        i++

    }
    db.close()
}

我已经尝试阅读 Android Studio 的官方文档,但它无法解决我的具体问题。

在您的 class MyViewHolder 中,您有称为绑定的方法,您还需要实现它并添加参数 应该是

class MyViewHolder(private val binding: CellCardsBinding): RecyclerView.ViewHolder(binding.root ) {
    fun bind(data:MyObject) {
        binding.yourView=data.title ...
    }
}

在 onBindViewHolder

..
holder.bind(myObject)

After switching from removing kotlin_extensions and switching to view binding, I received a "Unresolved reference: myViewHolder" in my onBindViewHolder method

嗯,您的 onBindViewHolder 方法正在传递一个名为 holder 的变量,而您正试图使用​​一个名为 myViewHolder 的变量,所以这似乎是个问题。

// --------------------this-----v
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

    val myObject = list[position]
    // v--- doesn't match this
    myViewHolder.bind(myObject) 

and when I replace "myViewHolder" with "holder", it then gives me a "Unresolved reference: bind". How do I resolve this.

您的 MyViewHolder class 有一个名为 binding 的方法,它不带任何参数。没有接受“myObject”的bind方法。

class MyViewHolder(val binding: CellCardsBinding): RecyclerView.ViewHolder(binding.root ) {
    fun binding() {

    }
}

编辑

You should pass an instance of the data class

class MyViewHolder(val binding: CellCardsBinding): RecyclerView.ViewHolder(binding.root ) {
        fun bind(object: MyObject) {
            // Set variables on binding
        }
    }

然后通过 onBindViewHolder:

从您的列表中传递一个实例
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

    val myObject = list[position]
    holder.bind(myObject) 

请检查 this blog post 了解更多。

我得到答案了。

class MyAdapter(private val context: Context, private val mHelper : TaskDbHelper) : RecyclerView.Adapter<MyAdapter.MyViewHolder>(),
    SwipeAndDragHelper.ActionCompletionContract {
    class MyViewHolder(val binding: CellCardsBinding): RecyclerView.ViewHolder(binding.root ) {

        private val titleView: TextView = itemView.findViewById<View>(R.id.title) as TextView
        val textView: TextView = itemView.findViewById<View>(R.id.text) as TextView
        private val dateTextView: TextView = itemView.findViewById<View>(R.id.date) as TextView

        fun binding (myObject: MyObject) {

            titleView.text = myObject.title
            textView.text = myObject.text
            dateTextView.text = myObject.date

        }
    }

我只是初始化了我想在我的布局中引用的视图,并在 binding() 函数中调用它们。