我已经实现了RecyclerView.ViewHolder子类,如下所示:
class PersonViewHolder(itemView: View, binding: ViewDataBinding) : RecyclerView.ViewHolder(itemView) { }
现在我试图在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
}
}
但编译器抱怨 - Unresolved reference: binding
以下是完整的实施:
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) { }
}
如果我在这里遗失任何东西,有什么想法?请建议。
答案 0 :(得分:5)
binding: ViewDataBinding
- 您只定义构造函数参数,它永远不会保存为类的成员。使用var
或val
标记它以使其存储参数并在以后可以访问它。