This article is the third in a series of articles that introduces the introduction of RecyclerView If you already have a certain understanding of creating RecyclerView, please continue reading this article. If you are not already familiar with it, I suggest you read first article this series.
When using RecyclerView
display list data, you may need to respond to click events of list elements. The response processing includes: opening a page containing more data, displaying a toast, deleting an element, and so on. Although the related response events are countless, they all need to be implemented onClick()
defines the click action
Before creating the listener, add a function to the Activity class to handle the response operation after the click.
<!-- Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
private fun adapterOnClick(flower: Flower) {
val intent = Intent(this, FlowerDetailActivity()::class.java)
intent.putExtra(FLOWER_ID, flower.id)
this.startActivity(intent)
}
Next, modify the constructor of the Adapter to pass in the onClick() function.
<!-- Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
class FlowersAdapter(private val onClick: (Flower) -> Unit) :
ListAdapter<Flower, RecyclerView.ViewHolder>(FlowerDiffCallback())
In the Activity class, pass in the click event function just created when initializing the Adapter.
<!-- Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
val flowersAdapter = FlowersAdapter { flower ->
adapterOnClick(flower)
}
add onClickHandler()
Now that the response processing has been defined, it can be associated with the ViewHolder of the Adapter.
Modify ViewHolder and pass in onClick() as a parameter.
<!-- Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
class FlowerViewHolder(itemView: View, val onClick: (Flower) -> Unit) :
RecyclerView.ViewHolder(itemView)
In the initialization code, call itemView's setOnClickListener{}.
<!-- Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
init {
itemView.setOnClickListener {
currentFlower?.let {
onClick(it)
}
}
}
Get it done! Now your RecyclerView
can respond to click events.
Happy programming!
Next
complete example that includes onClick().
Thank you for reading the third article of RecyclerView series Please continue to pay attention to more about RecyclerView
in the future.
If you want to know more about onClick(), please refer to official document .
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。