RecyclerView.Adapter 点击 kotlin
时间: 2023-12-17 14:48:07 浏览: 75
RecycleView通用Adapter(Kotlin语言)
您可以在 Kotlin 中使用以下代码来为 RecyclerView.Adapter 中的项目添加点击事件:
1. 在 ViewHolder 类中添加一个点击事件处理程序:
```kotlin
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
// 处理点击事件
}
}
}
```
2. 在 Activity 或 Fragment 中为 RecyclerView 添加一个 OnItemClickListener 接口:
```kotlin
interface OnItemClickListener {
fun onItemClick(view: View, position: Int)
}
```
3. 在 Adapter 类中添加一个 OnItemClickListener 成员变量和一个设置 OnItemClickListener 的方法:
```kotlin
class MyAdapter(private val items: List<String>) : RecyclerView.Adapter<MyViewHolder>() {
private var onItemClickListener: OnItemClickListener? = null
fun setOnItemClickListener(listener: OnItemClickListener) {
onItemClickListener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_layout, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.itemView.setOnClickListener {
onItemClickListener?.onItemClick(holder.itemView, position)
}
}
override fun getItemCount(): Int = items.size
}
```
4. 在 Activity 或 Fragment 中设置 OnItemClickListener:
```kotlin
val adapter = MyAdapter(items)
adapter.setOnItemClickListener(object : OnItemClickListener {
override fun onItemClick(view: View, position: Int) {
// 处理点击事件
}
})
recyclerView.adapter = adapter
```
阅读全文