gpt4 book ai didi

java - 在适配器类中获取 ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-11-30 05:08:27 25 4
gpt4 key购买 nike

当我点击项目时,我得到

java.lang.ArrayIndexOutOfBoundsException: length = 10; index = -1

这是我的onCreateViewHolder方法,当我单击项目时,我想打开 DetailActivity 并发送有 Intent 的数据

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.alphabet_item, parent, false)
val holder = ViewHolder(view)
view.setOnClickListener {
val intent = Intent(parent.context, ItemAlphabetDetailActivity::class.java)
intent.putExtra("NAME", alphabets[holder.position].context)/*
intent.putExtra("CONTEXT", alphabets[holder.adapterPosition].context)
intent.putExtra("IMAGE", alphabets[holder.adapterPosition].image)
intent.putExtra("SOUND", alphabets[holder.adapterPosition].sound)*/
parent.context.startActivity(intent)
}
return ViewHolder(view)
}

这是我的类ItemAlphabetAdapter

class ItemAlphabetAdapter(
private val alphabets: ArrayList<ItemAlphabet>
) : RecyclerView.Adapter<ItemAlphabetAdapter.ViewHolder>() {


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.alphabet_item, parent, false)
val holder = ViewHolder(view)
view.setOnClickListener {
val intent = Intent(parent.context, ItemAlphabetDetailActivity::class.java)
intent.putExtra("NAME", alphabets[holder.position].context)/*
intent.putExtra("CONTEXT", alphabets[holder.adapterPosition].context)
intent.putExtra("IMAGE", alphabets[holder.adapterPosition].image)
intent.putExtra("SOUND", alphabets[holder.adapterPosition].sound)*/
parent.context.startActivity(intent)
}
return ViewHolder(view)
}

override fun getItemCount(): Int = alphabets.size


override fun onBindViewHolder(holder: ItemAlphabetAdapter.ViewHolder, position: Int) {

val alphabet = alphabets[position]
holder.name.text = alphabet.name
holder.image.visibility = alphabet.image
}

class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val image: ImageView = itemView.findViewById(R.id.alphabet_image)
val name: TextView = itemView.findViewById(R.id.alphabet_name)

}

}

最佳答案

您必须编写以下代码

val intent = Intent(parent.context, ItemAlphabetDetailActivity::class.java)
intent.putExtra("NAME", alphabets[holder.position].context)/*
intent.putExtra("CONTEXT", alphabets[holder.adapterPosition].context)
intent.putExtra("IMAGE", alphabets[holder.adapterPosition].image)
intent.putExtra("SOUND", alphabets[holder.adapterPosition].sound)*/
parent.context.startActivity(intent)

在 onBindViewHolder() 中,它已经将您的位置作为参数之一

关于java - 在适配器类中获取 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54125718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com