Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best place to attach onClickListener in recyclerview

While i was looking at some tutorials about recycler view.some of them used the viewHolder constructor to attach the onClick listener while some of them used the onBindViewHolder method. which method is the best place to attach the onclicklistener. i'm really confused

like image 487
Sony Avatar asked Mar 06 '15 17:03

Sony


People also ask

Where do you add the android onClick attribute to make items in a RecyclerView respond to clicks?

Where do you add the android:onClick attribute to make items in a RecyclerView respond to clicks? In the layout file that displays the RecyclerView, add it to the element. Add it to the layout file for an item in the row.

What is the difference between onCreateViewHolder and onBindViewHolder?

This method internally calls onBindViewHolder to update the ViewHolder contents with the item at the given position and also sets up some private fields to be used by RecyclerView. This method calls onCreateViewHolder to create a new ViewHolder and initializes some private fields to be used by RecyclerView.


2 Answers

The method onBindViewHolder is called every time when you bind your view with data. So there is not the best place to set click listener. You don't have to set OnClickListener many times for the one View. So the best solution is to set click listener in onCreateViewHolder method. But the important thing is a how do you implement on click listener. If you for example want to get some model from list you can use getAdapterPosition() method from ViewHolder.

Look at the exmaple

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

    final View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.view_magazine_list_item, null);

    final ViewHolder result = new ViewHolder(view);
    view.setOnClickListener(new OnClickListener(){
          @Override
          public void onClick(View v){
             YourObject yourobject = yourObjectsList.get(result.getAdapterPosition()));
          }
    });
    return result;
}
like image 106
Konrad Krakowiak Avatar answered Nov 09 '22 19:11

Konrad Krakowiak


In ViewHolder is the better place:

public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    //views declare here

    public ItemViewHolder(View convertView)
    {
        super(convertView);

        ... ...

        convertView.setOnClickListener(this);
    }



    @Override
    public void onClick(View v)
    {
       //do something to view here
           //also you can get view position by 'getPosition()' here     

    }


}
like image 44
Xcihnegn Avatar answered Nov 09 '22 19:11

Xcihnegn