我是android和kotlin的新手。我正在使用接口为我的 cardViewAdapter 制作 onclick 监听器,这样我就可以从我的活动中覆盖它的回调。但是我在模拟器上运行它并单击每个 itemView 时收到错误“lateinit 属性 onItemClick 尚未初始化”。
在我的代码中,我尝试在函数中对其进行初始化。在此之前,我尝试了另一个答案,所以https://stackoverflow.com/a/46076355/7587265 但 onclick 不起作用
这是我的 MainActivity.kt
rvMotor.layoutManager = GridLayoutManager(this, 2)
val recycleViewAdapter = CardViewMainAdapter(listMotor)
recycleViewAdapter.setOnItemClickCallback(object : CardViewMainAdapter.OnItemClickCallback{
override fun onItemClicked(data: Motor) {
val intent = Intent(this@MainActivity, DetailActivity::class.java)
intent.putExtra(DetailActivity.EXTRA_ID, data.id)
startActivity(intent)
}
})
rvMotor.adapter = recycleViewAdapter
这是我的 CardViewMainAdapter.kt
class CardViewMainAdapter(private val listMotors: ArrayList<Motor>) :
RecyclerView.Adapter<CardViewMainAdapter.CardViewMainViewHolder>() {
private lateinit var onItemClickCallback : OnItemClickCallback
fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback){
this.onItemClickCallback = onItemClickCallback
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewMainViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(R.layout.cardview_main, parent, false)
return CardViewMainViewHolder(view)
}
override fun getItemCount(): Int {
return listMotors.size
}
override fun onBindViewHolder(holder: CardViewMainViewHolder, position: Int) {
val motor = listMotors[position]
holder.cvMainName.text = motor.name
Glide.with(holder.itemView.context)
.load(motor.image)
.apply(RequestOptions().override(350, 550))
.into(holder.cvMainImage)
holder.itemView.setOnClickListener{
onItemClickCallback.onItemClicked(listMotors[holder.adapterPosition])
}
}
inner class CardViewMainViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
var cvMainImage: ImageView = itemView.findViewById(R.id.cardview_main_img)
var cvMainName: TextView = itemView.findViewById(R.id.cardview_main_txt)
}
interface OnItemClickCallback {
fun onItemClicked(data: Motor)
}
}