Reputation: 21
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.todo_layout, parent, false)
return TodoViewHolder(view)
}
override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
holder.itemView.apply {
}
}
override fun getItemCount(): Int {
return todos.size
}
}
Here is the adapter class.
Link to layout xml file for adapter class
What I want is to access the checkbox and textview from xml file inside
holder.itemView.apply{
tvTask.text = todos[position].title
cbTask.isChecked = todos[position].isChecked
}
title and isChecked are variables declared in a data class of string and boolean type respectively
My inner class contains itemViews since I am trying to make a To-Do app. So it returns items to the constructor.
Upvotes: 0
Views: 245
Reputation: 1102
To enable ViewBinding, add the following piece of code to the app-level build.gradle file.
android {
...
buildFeatures {
viewBinding true
}
}
XML file is wrapped with layout
tag and that seems to be fine.
And now refactor the ViewHolder class's constructor to take a binding
variable.
inner class TodoViewHolder(val binding: TodoLayoutBinding) : RecyclerView.ViewHolder(binding.root)
note: inner
modifier is optional here.
The binding
variable can be accessed in the onBindViewHolder
method's holder
variable.
override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
holder.binding.apply {
// ...access the views here...
}
}
Upvotes: 1