由于这是我第一次在Kotlin编程,所以我在网上学习了一个教程,我只是想将我将从数据库中的表中获得的文本绑定到一个ViewModel上,我从一个我在网上看到的例子开始:
在这段代码中,我收到一个关于"itemView.userName.text="test"的错误,它不能识别‘用户名’,我不知道为什么.
使用此适配器
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>
我已经try 了一个更简单的布局,只有一个文本视图,清理和重建项目,但我不能让它工作