如何解决无法在 RecyclerView 中绑定数据
我正在尝试学习移动开发,但在尝试进行 recyclerview 时遇到了困难。
我已经设置了数据类以及项目的 xml 文件。
当我尝试将数据绑定到 xml 文件时,在 onBindViewHolder 函数中,系统没有给我选择要绑定到哪个 ID 的选项。
数据类
package com.example.recyclerview1
data class Todo(
val title: String,var isChecked: Boolean
)
XML 项目
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="100dp"
android:padding="16dp">
<TextView
android:id="@+id/tvTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="title"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/cbDone"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="@+id/cbDone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
适配器类
package com.example.recyclerview1
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
class TodoAdapter(
var todos:List<Todo>
): RecyclerView.Adapter<TodoAdapter.TodoViewHolder>() {
inner class TodoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup,viewType: Int): TodoViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_todo,parent,false)
return TodoViewHolder(view)
}
override fun getItemCount(): Int { return todos.size}
override fun onBindViewHolder(holder: TodoViewHolder,position: Int) {
holder.itemView.tvTitle << right here I want to select the ID of the TextView,but the IDE does not show me
}
}
解决方法
不能进行数据绑定,而 XML 不会生成数据绑定。该项目 XML 需要 layout
& data
节点,模型类可能需要 @Bindable
注释。使用数据绑定更好地膨胀,但为此需要生成数据。
您可以使用 findViewById
方法获取视图组件的实例,然后对它们执行一些操作,如下所示:
class TodoAdapter(var todos:List<Todo>) : RecyclerView.Adapter<TodoAdapter.TodoViewHolder>() {
inner class TodoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
{
var tvTitle: TextView = itemView.findViewById(R.id.tvTitle)
var cbDone: CheckBox = itemView.findViewById(R.id.cbDone)
}
override fun onBindViewHolder(holder: TodoViewHolder,position: Int) {
holder.tvTitle. // DO YOUR STUFF HERE
}
}
或者您可以使用 ViewBinding
功能来访问视图实例,例如 this post 中编写的内容。
如果要在 XML 中执行整个数据绑定,则需要使用 DataBinding
功能。为此,只需按照 this post 了解如何启用 DataBinding 以及如何在您的项目中使用它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。