This is the third in a series of articles which cover the fundamentals of creating and using RecyclerView
. If you already have a solid understanding of how to create a RecyclerView
, then carry on. Otherwise, consider starting with this post.
When displaying a list of data with RecyclerView
, you may want to have a response when an item is clicked. This response could open a new page with more data, present a toast, remove an item, etc. The possibilities are endless but they are all done using onClick()
.
From our partners:
Defining the click action
Before creating the listener, create a function in the Activity
class that performs the action to be done upon 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, update the Adapter’s
constructor to take 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 newly created function when you initialize the Adapter
.
<!-- Copyright 2019 Google LLC. SPDX-License-Identifier: Apache-2.0 --> val flowersAdapter = FlowersAdapter { flower -> adapterOnClick(flower) }
Adding the onClickHandler()
Now that the action is defined, it is time to attach it to the ViewHolder
in the Adapter
.
Update the ViewHolder
to take 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 initializer, call setOnClickListener{}
on the itemView
.
<!-- Copyright 2019 Google LLC. SPDX-License-Identifier: Apache-2.0 --> init { itemView.setOnClickListener { currentFlower?.let { onClick(it) } } }
That’s it! Your RecyclerView
is now responsive so time to get your click on!
Happy coding!
Next Steps
The full code sample including onClick()
can be found here.
Thank you for reading the third installment in my RecyclerView
series! Stay tuned as I write about more RecyclerView
features.
If you want to learn more about onClick()
check out the documentation.
Source Medium by Meghan Mehta
For enquiries, product placements, sponsorships, and collaborations, connect with us at [email protected]. We'd love to hear from you!
Our humans need coffee too! Your support is highly appreciated, thank you!