RecyclerView点击子项跳转kotlin
时间: 2023-12-17 17:29:01 浏览: 136
以下是在Kotlin中实现RecyclerView点击子项跳转的示例代码:
1. 在RecyclerView的Adapter中设置子项点击事件监听器:
```kotlin
class MyAdapter(private val itemList: List<Item>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
private var listener: OnItemClickListener? = null
fun setOnItemClickListener(listener: OnItemClickListener) {
this.listener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = itemList[position]
holder.textView.text = item.text
holder.itemView.setOnClickListener {
listener?.onItemClick(item)
}
}
override fun getItemCount(): Int {
return itemList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.findViewById(R.id.text_view)
}
interface OnItemClickListener {
fun onItemClick(item: Item)
}
}
```
2. 在Activity或Fragment中实现OnItemClickListener接口,并在onCreateView方法中设置RecyclerView的Adapter和点击事件监听器:
```kotlin
class MyFragment : Fragment(), MyAdapter.OnItemClickListener {
private lateinit var recyclerView: RecyclerView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_layout, container, false)
recyclerView = view.findViewById(R.id.recycler_view)
recyclerView.layoutManager = LinearLayoutManager(context)
val itemList = listOf(Item("Item 1"), Item("Item 2"), Item("Item 3"))
val adapter = MyAdapter(itemList)
adapter.setOnItemClickListener(this)
recyclerView.adapter = adapter
return view
}
override fun onItemClick(item: Item) {
// 处理子项点击事件,跳转到其他Activity或Fragment
val intent = Intent(context, DetailActivity::class.java)
intent.putExtra("text", item.text)
startActivity(intent)
}
}
```
阅读全文