Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I place setOnClickListener in a RecyclerView Adapter

In tutorials on internet where they setOnClickListener in Adapter of RecyclerView they define it in two ways : either inside ViewHolder or inside BindViewHolder.

My Question is which one is a better approach, Please recommend any another approach if available

1) inside ViewHolder:

public static class ViewHolder extends RecyclerView.ViewHolder {

    public ViewHolder(View itemView) {
        super(itemView);
        tvSrc = (TextView) itemView.findViewById(R.id.tvSrc);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(v.getContext(), "inside viewholder position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
            }
        });
    }

2) inside BindViewHolder

public void onBindViewHolder(DisplayTrainsAdapter.ViewHolder viewHolder, final int position) {

    viewHolder.tvSrc.setText(mDataset.get(position).strSrc);
    viewHolder.tvSrc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(v.getContext(), "position = " + getItemId(position), Toast.LENGTH_SHORT).show();
        }
    });
}    
like image 770
Anudeep Samaiya Avatar asked Apr 09 '15 11:04

Anudeep Samaiya


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.

How do I use RecyclerView adapter?

This method calls onCreateViewHolder to create a new ViewHolder and initializes some private fields to be used by RecyclerView. Returns the position of the given ViewHolder in the given Adapter . Returns the total number of items in the data set held by the adapter. Return the stable ID for the item at position .


1 Answers

Your number 1 solution is the best as you proposed since that assignment will not be called in the Binding at each invalidate triggered by notify..() methods. I know also others solutions but you need to implement android.view.GestureDetector in your activity.

If you want others improvements on the adapter, take a look at mine FlexibleAdapter https://github.com/davideas/FlexibleAdapter and feel free to implement in your project.

like image 180
Davideas Avatar answered Sep 17 '22 08:09

Davideas