Bill
Bill

Reputation: 3209

Viewholders and setOnClickListeners

I have a RecyclerView with a list of items. The individual list item is an ImageView with a TextView. They have different behaviours when clicked. The individual list item is rendered with the aid of a ViewHolder.

Where should I put the .setOnClickListener() call for the ImageView and TextView? In the ViewHolder? Or inside the RecyclerView's onBindViewHolder method when the view is binded?

Upvotes: 0

Views: 77

Answers (2)

Sid
Sid

Reputation: 14916

From the official doc of ViewHold:

A ViewHolder describes an item view and metadata about its place within the RecyclerView.

So you should avoid do anything else in the viewhold, instead use onBindViewHolder in the RecyclerView

If you take a look at the example made by Google of RecyclerView on GitHub you will see google does not set listeners in the ViewHolder

Upvotes: 1

Bidhan
Bidhan

Reputation: 10697

Call it inside of the onBindViewHolder method while you're binding your ImageView and TextView. If you set it on the ViewHolder itself, then the onClick() will be triggered for the entire list item in the RecyclerView .

Upvotes: 1

Related Questions