maybe there is a simple reason. I cannot find it... My findViewById does not find any IDs of my project. So, R.id.name cannot be found, same for R.layout.item.
This is my code:
class RVAdapter(persons: List<Person>?): RecyclerView.Adapter<RVAdapter.PersonViewHolder>() {
inner class PersonViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var cv: CardView
var personName: TextView
var personAge: TextView
init {
cv = this.itemView.findViewById(R.id.cv)
personName = this.itemView.findViewById(R.id.person_name)
personAge = this.itemView.findViewById(R.id.person_honor)
}
}
var persons: List<Person>? = null
init {
this.persons = persons
}
override fun getItemCount(): Int {
return persons!!.size
}
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): PersonViewHolder {
val v: View =
LayoutInflater.from(viewGroup.context).inflate(R.layout.item, viewGroup, false)
return PersonViewHolder(v)
}
override fun onBindViewHolder(personViewHolder: PersonViewHolder, i: Int) {
personViewHolder.personName.text = persons!![i].name
personViewHolder.personAge.setText(persons!![i].honor)
}
}
The IDs are in a XML file definitly excactly like in the code. I put
buildFeatures{
viewBinding=true
}
to my gradle file but it doesn´t work.
Any ideas?
CodePudding user response:
Remove R package and re-import it. May be there is the problem while we copy paste the codes.
Or you can use binding in your adapter -> https://www.geeksforgeeks.org/how-to-use-view-binding-in-recyclerview-adapter-class-in-android/
CodePudding user response:
Holder Class
inner class PersonViewHolder(val binding: LayoutItemBinding) :
RecyclerView.ViewHolder(binding.root)
onCreateviewHolder override method
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PersonViewHolder{
return PersonViewHolder(
LayoutItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)}
onBindViewHolder override method
override fun onBindViewHolder(holder: PersonViewHolder, position: Int) {
holder.binding.name.text="what you need"
}