ViewHolder无法识别使用Kotlin绑定的文本视图

agyaoht7  于 7个月前  发布在  Kotlin
关注(0)|答案(1)|浏览(84)

我在网上学习了一个教程,因为这是我第一次用Kotlin编程,我只是想把我从数据库中的表中获取的文本绑定到ViewModel,我从一个我在网上看到的例子开始作为基础:
在这段代码中,我在“itemView.userName.text =“test”"上得到一个错误,它不识别“userName”,我不知道为什么。
与这个适配器

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.timetally.R
import com.example.timetally.repository.entity.TaskType

class TaskTypeAdapter : RecyclerView.Adapter<TaskTypeAdapter.ViewHolder>() {

    private var taskTypeList = emptyList<TaskType>()

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(taskType: TaskType) {
            itemView.userName.text = "test"
        }
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(taskTypeList[position])
    }

    override fun getItemCount(): Int = taskTypeList.size

    fun setData(userLtaskTypeListist: List<TaskType>) {
        this.taskTypeList = taskTypeList
        notifyDataSetChanged()
    }
}

字符串
使用这个xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">
    <TextView
        android:id="@+id/userName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp" />
    <TextView
        android:id="@+id/userEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="@android:color/darker_gray" />
    <TextView
        android:id="@+id/userPhone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="@android:color/darker_gray" />
    <TextView
        android:id="@+id/userWebsite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="@android:color/darker_gray" />
</LinearLayout>


我已经尝试了一个简单的布局,只有一个textView,清洁和重建项目,但我不能让它工作

wh6knrhe

wh6knrhe1#

这不是在android中使用视图绑定的方法。首先在你的模块的gradle中你必须启用视图绑定功能:

android {
    ...
    buildFeatures {
        viewBinding = true
    }
}

字符串
之后,在视图保持器中,您可以创建绑定示例并使用它:

class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    private val binding = TaskTypeLayoutBinding.bind(itemView)

    fun bind(taskType: TaskType) {
        binding.userName.text = "test"
    }
}


当您启用视图绑定功能时,将为所有布局自动生成一个绑定类。

相关问题