0

What is the current preffered approach for setting up clicklistener for recyclerview items?

3 Answers3

0

RecyclerView does not have special method attaching click handlers to items unlike ListView. To achieve a similar effect manually, we can attach click listener within the ViewHolder inside our adapter:

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public TextView tvName;

    public ViewHolder(View itemView) {
        super(itemView);
        this.tvName = (TextView) itemView.findViewById(R.id.tvName);
        this.tvName.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        // some code
    }
}
Anton K
  • 102
  • 1
  • 8
  • Thank you , I'm already using this pattern. What do I need to do if I need click listener for just one item (like a textview?) instead of the whole row? –  Jun 24 '16 at 14:07
  • I've update the answer for your case – Anton K Jun 24 '16 at 14:28
0

Better to handle onClick() method in viewHolder constructor

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public ViewHolder(View itemView) {
        super(itemView);
        itemView.findViewById(R.id.foo).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

    }
}
Sairam
  • 169
  • 12
0

Try those links, this might help You:

http://www.codexpedia.com/android/defining-item-click-listener-for-recyclerview-in-android/ http://antonioleiva.com/recyclerview-listener/

R. Zagórski
  • 20,020
  • 5
  • 65
  • 90
  • I'm using that exact pattern as codexpedia and it works. When I click a row , my code executes. But I would like different action for different item clicks. Like clicking on the image in a row sends you to activity A , clicking on rest of the row sends you to activity B. Could you modify that code for this purpose? –  Jun 24 '16 at 14:17
  • I would suggest reacting to click event based on clicked position. The `ItemClickListener` in the first approach passes position as the second parameter of it's method `onClick`. – R. Zagórski Jun 24 '16 at 14:29