我正在尝试在Kotlin中编写我的第一个RecyclerView
自定义适配器。每个View
都非常简单,它是CardView
,上面有图片+名称。
我面临两个问题:
错误1 - fun bindItems
在我尝试以下命名时给出错误:
// 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
错误2 - onBindViewHolder
不允许我添加这样的监听器:
holder.bindItems(user[position])
holder.setOnClickListener{
//do whatever
}
这里是适配器的完整代码:
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)
}
}
}
我不确定这是否是我的错误2的答案,但......以下似乎有效:
holder.itemView.setOnClickListener({
// do something here
})
答案 0 :(得分:4)
我在适配器中使用setOnClickListener,如下所示:
holder.itemView.setOnClickListener(){
}
它完美地为我工作。