'Kotlin - RecyclerView.ViewHolder subclass - unable to access an extra property
I have implemented RecyclerView.ViewHolder sub-class as below:
class PersonViewHolder(itemView: View, binding: ViewDataBinding) : RecyclerView.ViewHolder(itemView) { }
Now I am trying to access binding property declared in it like this within subclass of RecyclerView.Adapter:
override fun onBindViewHolder(holder: PersonViewHolder?, position: Int) {
val person = persons[position]
if (holder != null) {
holder.binding.setVariable(BR.person, person) // line with error
holder.binding.executePendingBindings() // line with error
}
}
But compiler is complaining - Unresolved reference: binding
Here is the complete implementation:
class PersonsAdapter(private var persons: Array<Person>) : RecyclerView.Adapter<PersonsAdapter.PersonViewHolder>() {
override fun onBindViewHolder(holder: PersonViewHolder?, position: Int) {
val person = persons[position]
if (holder != null) {
holder.binding.setVariable(BR.person, person)
holder.binding.executePendingBindings()
}
}
override fun getItemCount(): Int {
return persons.size
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): PersonViewHolder {
val itemView = LayoutInflater.from(parent!!.context).inflate(R.layout.list_item_person, parent, false)
return PersonViewHolder(itemView, DataBindingUtil.bind(itemView))
}
class PersonViewHolder(itemView: View, binding: ViewDataBinding) : RecyclerView.ViewHolder(itemView) { }
}
Any ideas if I am missing anything over here? Please suggest.
Solution 1:[1]
binding: ViewDataBinding - you're only defining a constructor parameter, it is never saved as a member of the class. Mark it using var or val to have it store the parameter and have it be accessible later on.
Solution 2:[2]
check build.gradle file (module level) in your project
in the top android extesion plugin is included or not? plugin { id 'kotlin-android-extensions' }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kiskae |
| Solution 2 | Sundeep Sharma |
