在学习使用RecyclerView时
对Adapter的几个主要方法进行重写
通过使用书中的例子
在onCreateViewHolder中使用
viewHolder.itemView.setOnClickListener { val position = viewHolder.adapterPosition val fruit = fruitList[position] Toast.makeText(parent.context,"You clicked view " + fruit.name, Toast.LENGTH_SHORT).show() }
然而不知什么原因
获取到的position值总是-1
最后通过各种查询都没找到直接的解决办法(没有代码可以直接抄
但是收获了解决的思路就是尝试在onBindViewHolder中实现
holder.itemView.setOnClickListener { val position = holder.adapterPosition val fruit = fruitList[position] Toast.makeText(holder.itemView.context,"You clicked view " + fruit.name, Toast.LENGTH_SHORT).show() }
下面给出重写的onBindViewHolder的完整代码
override fun onBindViewHolder(holder: ViewHolder, position: Int) { val fruit = fruitList[position] holder.fruitImage.setImageResource(fruit.imageId) holder.fruitName.text = fruit.name holder.itemView.setOnClickListener{ val position = holder.adapterPosition val fruit = fruitList[position] Toast.makeText(holder.itemView.context,"You clicked view " + fruit.name, Toast.LENGTH_SHORT).show() } holder.fruitImage.setOnClickListener{ val position = holder.adapterPosition val fruit = fruitList[position] Toast.makeText(holder.itemView.context,"You clicked view " + fruit.name, Toast.LENGTH_SHORT).show() } }
注: onCreateViewHolde方法中的parent.context就相当于onBindViewHolder中的holer.itemView.context
(可能描述不是很准确,但效果是相当的