Reputation: 5739
I am trying to write my first RecyclerView
custom adapter in Kotlin. Each View
is pretty simple, it is a CardView
with picture + name on it.
I am facing two problems:
ERROR 1 - fun bindItems
is giving me error when i try the following to assign the name:
// THIS DOES GIVE ME ERROR, IT MARKS txvW_recycItem_userName IN RED
itemView.txvW_recycItem_userName = user.name
// HOWEVER THIS WORKS
val tvw_name = itemView.findViewById(R.id.txvW_recycItem_userName) as TextView
tvw_name.text = user.name
ERROR 2 - onBindViewHolder
does not let me add a listener like this:
holder.bindItems(user[position])
holder.setOnClickListener{
//do whatever
}
And here it is the complete code for the adapter:
class CustomRecyclerAdapter(var user : ArrayList<Users>) : RecyclerView.Adapter<CustomRecyclerAdapter.MyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomRecyclerAdapter.MyViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.recycler_item, parent, false)
return MyViewHolder(v)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int){
holder.bindItems(user[position])
}
override fun getItemCount() = user.size
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(user : Users){
// HERE IT IS THE LINE DESCRIBED ON ERROR 1
//itemView.txvW_recycItem_userName = user.name
val image = itemView.findViewById(R.id.imgvW_mainPic) as ImageView
val tvw_name = itemView.findViewById(R.id.txvW_recycItem_userName) as TextView
tvw_name.text = user.name
image.setImageResource(user.image)
}
}
}
I am not sure if that is an answer for my ERROR 2 but...the following seems to be working:
holder.itemView.setOnClickListener({
// do something here
})
Upvotes: 2
Views: 2286
Reputation: 1323
I am using setOnClickListener in adapter like this :
holder.itemView.setOnClickListener(){
}
its perfectly working for me.
Upvotes: 4