adapterPosition方法返回-1 无法获取位置

RecycleView关于** position = viewHolder.adapterPosition不能返回正确值而是返回-1**
在学习第一行代码第三版的时候,发现书中关于RecycleView的点击事件是这么处理的:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
 val view = LayoutInflater.from(parent.context)
 .inflate(R.layout.fruit_item, parent, false)
 val viewHolder = ViewHolder(view)
 viewHolder.itemView.setOnClickListener {
 val position = viewHolder.adapterPosition
 val fruit = fruitList[position]
 Toast.makeText(parent.context, "you clicked view ${fruit.name}",
 Toast.LENGTH_SHORT).show()
 }
 viewHolder.fruitImage.setOnClickListener {
 val position = viewHolder.adapterPosition
 val fruit = fruitList[position]
 Toast.makeText(parent.context, "you clicked image ${fruit.name}",
 Toast.LENGTH_SHORT).show()
 }
 return viewHolder
 }

但是无法一运行就奔溃,输出position值为-1,所以有问题。
应该在onBindViewHolder中加入点击事件,并且由于自带position就不需要重新获取position直接使用就可以了

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val fruit = fruitList[position]
        holder.fruitImage.setImageResource(fruit.imageId)
        holder.fruitName.text = fruit.name
        holder.itemView.setOnClickListener {
            Toast.makeText(holder.itemView.context, "you click view ${fruit.name}",Toast.LENGTH_SHORT ).show()
        }
        holder.fruitImage.setOnClickListener {
            Toast.makeText(holder.itemView.context, "you click image ${fruit.name}",Toast.LENGTH_SHORT ).show()
        }
    }
posted @ 2022-09-05 10:33  一无所知小白龙  阅读(475)  评论(0编辑  收藏  举报