可以在ChatHeaderTemplateAdapter中的convert方法中为每个文本增加一个单击事件,并获取对应的文本内容。具体实现如下:
class ChatHeaderTemplateAdapter(data: MutableList, private val listener: OnItemClickListener) :
BaseRecyclerAdapter(R.layout.item_chat_header_template, data) {
override fun convert(holder: RecyclerViewHolder, item: String) {
holder.setText(R.id.tv_template_content, item)
holder.itemView.setOnClickListener {
listener.onItemClick(item)
}
}
interface OnItemClickListener {
fun onItemClick(content: String)
}
}
然后在initChatHeaderRecycler方法中传入OnItemClickListener,如下所示:
private fun initChatHeaderRecycler(headerRv: CommonRecyclerView) {
val layoutManager = LinearLayoutManager(this)
val templateAdapter =
ChatHeaderTemplateAdapter(mutableListOf("简单描述量子力学原理", "世界的起源", "怎样做红烧鱼", "假期去哪玩最有意义"), object : ChatHeaderTemplateAdapter.OnItemClickListener {
override fun onItemClick(content: String) {
// 获取对应的文本内容
Toast.makeText(this@MainActivity, content, Toast.LENGTH_SHORT).show()
}
})
headerRv.layoutManager = layoutManager
(headerRv.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
headerRv.adapter = templateAdapter
}
这样就可以为每个文本增加一个单击事件并获取对应的文本内容了。