gpt4 book ai didi

android - 如何在Kotlin中将onClickListener添加到recyclerView的项目中?

转载 作者:行者123 更新时间:2023-12-02 13:17:32 24 4
gpt4 key购买 nike

我正在使用recyclerView来显示Firebase数据库中的数据,我想处理点击,
现在重要的一点是,在显示下一个 Activity 之前,我想知道为了测试Google Play在应用结算中的点击次数
我的意思是用户应该单击项目编号1,然后付款以查看信息编号1,依此类推
有什么帮助吗?

//my adapter

class MyAdapter(
private val arrayList: ArrayList<Long>
) :
RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view =
LayoutInflater.from(parent.context)
.inflate(R.layout.layout_item, parent, false)
return MyViewHolder(view)
}

override fun getItemCount() = arrayList.size

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.number.text = arrayList[position].toString()
}

class MyViewHolder(view: View) :
RecyclerView.ViewHolder(view) {
val number = view.findViewById<View>(R.id.singleNumberId) as TextView
}

}

最佳答案

这是我注册RecyclerView适配器项的点击的一个小示例:

class PatientListAdapter : ListAdapter<Patient, PatientListAdapter.PatientViewHolder>(co.za.abcdefgh.viewmodels.PatientListViewModel.DiffItemCallback) {

// this property will be used to set the onclick callback for the entire adpater
var onPatientSelectedCallback: PatientSelectedCallback? = null

override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): PatientViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_patient, parent, false) as View
return PatientViewHolder(view)
}

override fun onBindViewHolder(holder: PatientViewHolder, position: Int) {
holder.view.item_patient_name.text = getItem(position).toString()
holder.view.item_patient_folderNumber.text = getItem(position).folderNumber

// lets set our on click for each viewholder here
holder.view.item_patient_info_card.setOnClickListener {
// the secret sauce .... getItem(holder.adapterPosition)
onPatientSelectedCallback?.onPatientSelected(getItem(holder.adapterPosition))
}
}

class PatientViewHolder(val view: View) : RecyclerView.ViewHolder(view)

// interface which defines a method signature that will called when a item in the adpater is selected
interface PatientSelectedCallback {
fun onPatientSelected(patient: Patient)
}
}

然后在实例化后使用适配器的任何地方只需执行以下操作:
val viewAdapter = PatientListAdapter()

viewAdapter.onPatientSelectedCallback =
object : PatientListAdapter.PatientSelectedCallback {
override fun onPatientSelected(patient: Patient) {
// do something with the chosen item
patientViewModel.setPatient(patient)
}
}

关于android - 如何在Kotlin中将onClickListener添加到recyclerView的项目中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62439162/

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