By Tarun Varshney


2014-07-22 10:43:39 8 Comments

I was exploring RecyclerView and I was surprised to see that RecyclerView does not have onItemClickListener(). Because RecyclerView extends

android.view.ViewGroup

and ListView extends

android.widget.AbsListView

. However I solved my problem by writing onClick in my RecyclerView.Adapter:

public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {

    public TextView txtViewTitle;
    public ImageView imgViewIcon;

    public ViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
        imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
    }

    @Override
    public void onClick(View v) {

    }
}

But still I want to know why Google removed onItemClickListener()?

Is there a performance issue or something else?

30 comments

@Daniele Segato 2016-03-10 13:12:54

An alternative solution is the one proposed by Hugo Visser, an Android GDE. He made a licence-free class available for you to just drop in your code and use it.

Edit 2019: kotlin version by me, java one, from Hugo Visser, kept below

Kotlin

Usage:

recyclerView.onItemClick { recyclerView, position, v ->
    // do it
}

(it also support long item click and see below for another feature I've added).

implementation (my adaptation to Hugo Visser Java code):

typealias OnRecyclerViewItemClickListener = (recyclerView: RecyclerView, position: Int, v: View) -> Unit
typealias OnRecyclerViewItemLongClickListener = (recyclerView: RecyclerView, position: Int, v: View) -> Boolean

class ItemClickSupport(private val recyclerView: RecyclerView) {

    private var onItemClickListener: OnRecyclerViewItemClickListener? = null
    private var onItemLongClickListener: OnRecyclerViewItemLongClickListener? = null

    private val attachListener: RecyclerView.OnChildAttachStateChangeListener by lazy {
        object : RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewAttachedToWindow(view: View) {
                // every time a new child view is attached add click listeners to it
                val holder = [email protected](view)
                        .takeIf { it is ItemClickSupportViewHolder } as? ItemClickSupportViewHolder

                if (onItemClickListener != null && holder?.isClickable != false) {
                    view.setOnClickListener(onClickListener)
                }
                if (onItemLongClickListener != null && holder?.isLongClickable != false) {
                    view.setOnLongClickListener(onLongClickListener)
                }
            }

            override fun onChildViewDetachedFromWindow(view: View) {

            }
        }
    }

    init {
        // the ID must be declared in XML, used to avoid
        // replacing the ItemClickSupport without removing
        // the old one from the RecyclerView
        this.recyclerView.setTag(R.id.item_click_support, this)
        this.recyclerView.addOnChildAttachStateChangeListener(attachListener)
    }

    companion object {
        fun addTo(view: RecyclerView): ItemClickSupport {
            // if there's already an ItemClickSupport attached
            // to this RecyclerView do not replace it, use it
            var support: ItemClickSupport? = view.getTag(R.id.item_click_support) as? ItemClickSupport
            if (support == null) {
                support = ItemClickSupport(view)
            }
            return support
        }

        fun removeFrom(view: RecyclerView): ItemClickSupport? {
            val support = view.getTag(R.id.item_click_support) as? ItemClickSupport
            support?.detach(view)
            return support
        }
    }

    private val onClickListener = View.OnClickListener { v ->
        val listener = onItemClickListener ?: [email protected]
        // ask the RecyclerView for the viewHolder of this view.
        // then use it to get the position for the adapter
        val holder = this.recyclerView.getChildViewHolder(v)
        listener.invoke(this.recyclerView, holder.adapterPosition, v)
    }

    private val onLongClickListener = View.OnLongClickListener { v ->
        val listener = onItemLongClickListener ?: [email protected] false
        val holder = this.recyclerView.getChildViewHolder(v)
        [email protected] listener.invoke(this.recyclerView, holder.adapterPosition, v)
    }

    private fun detach(view: RecyclerView) {
        view.removeOnChildAttachStateChangeListener(attachListener)
        view.setTag(R.id.item_click_support, null)
    }

    fun onItemClick(listener: OnRecyclerViewItemClickListener?): ItemClickSupport {
        onItemClickListener = listener
        return this
    }

    fun onItemLongClick(listener: OnRecyclerViewItemLongClickListener?): ItemClickSupport {
        onItemLongClickListener = listener
        return this
    }

}

/** Give click-ability and long-click-ability control to the ViewHolder */
interface ItemClickSupportViewHolder {
    val isClickable: Boolean get() = true
    val isLongClickable: Boolean get() = true
}

// Extension function
fun RecyclerView.addItemClickSupport(configuration: ItemClickSupport.() -> Unit = {}) = ItemClickSupport.addTo(this).apply(configuration)

fun RecyclerView.removeItemClickSupport() = ItemClickSupport.removeFrom(this)

fun RecyclerView.onItemClick(onClick: OnRecyclerViewItemClickListener) {
    addItemClickSupport { onItemClick(onClick) }
}
fun RecyclerView.onItemLongClick(onLongClick: OnRecyclerViewItemLongClickListener) {
    addItemClickSupport { onItemLongClick(onLongClick) }
}

(see below you also need to add an XML file)

Bonus feature of Kotlin version

Sometimes you do not want all the items of the RecyclerView to be clickable.

To handle this I've introduced the ItemClickSupportViewHolder interface that you can use on your ViewHolder to control which item is clickable.

Example:

class MyViewHolder(view): RecyclerView.ViewHolder(view), ItemClickSupportViewHolder {
    override val isClickable: Boolean get() = false
    override val isLongClickable: Boolean get() = false
}

Java

Usage:

ItemClickSupport.addTo(mRecyclerView)
        .setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
    @Override
    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
        // do it
    }
});

(it also support long item click)

Implementation (comments added by me):

public class ItemClickSupport {
    private final RecyclerView mRecyclerView;
    private OnItemClickListener mOnItemClickListener;
    private OnItemLongClickListener mOnItemLongClickListener;
    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mOnItemClickListener != null) {
                // ask the RecyclerView for the viewHolder of this view.
                // then use it to get the position for the adapter
                RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
                mOnItemClickListener.onItemClicked(mRecyclerView, holder.getAdapterPosition(), v);
            }
        }
    };
    private View.OnLongClickListener mOnLongClickListener = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            if (mOnItemLongClickListener != null) {
                RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
                return mOnItemLongClickListener.onItemLongClicked(mRecyclerView, holder.getAdapterPosition(), v);
            }
            return false;
        }
    };
    private RecyclerView.OnChildAttachStateChangeListener mAttachListener
            = new RecyclerView.OnChildAttachStateChangeListener() {
        @Override
        public void onChildViewAttachedToWindow(View view) {
            // every time a new child view is attached add click listeners to it
            if (mOnItemClickListener != null) {
                view.setOnClickListener(mOnClickListener);
            }
            if (mOnItemLongClickListener != null) {
                view.setOnLongClickListener(mOnLongClickListener);
            }
        }

        @Override
        public void onChildViewDetachedFromWindow(View view) {

        }
    };

    private ItemClickSupport(RecyclerView recyclerView) {
        mRecyclerView = recyclerView;
        // the ID must be declared in XML, used to avoid
        // replacing the ItemClickSupport without removing
        // the old one from the RecyclerView
        mRecyclerView.setTag(R.id.item_click_support, this);
        mRecyclerView.addOnChildAttachStateChangeListener(mAttachListener);
    }

    public static ItemClickSupport addTo(RecyclerView view) {
        // if there's already an ItemClickSupport attached
        // to this RecyclerView do not replace it, use it
        ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
        if (support == null) {
            support = new ItemClickSupport(view);
        }
        return support;
    }

    public static ItemClickSupport removeFrom(RecyclerView view) {
        ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
        if (support != null) {
            support.detach(view);
        }
        return support;
    }

    public ItemClickSupport setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
        return this;
    }

    public ItemClickSupport setOnItemLongClickListener(OnItemLongClickListener listener) {
        mOnItemLongClickListener = listener;
        return this;
    }

    private void detach(RecyclerView view) {
        view.removeOnChildAttachStateChangeListener(mAttachListener);
        view.setTag(R.id.item_click_support, null);
    }

    public interface OnItemClickListener {

        void onItemClicked(RecyclerView recyclerView, int position, View v);
    }

    public interface OnItemLongClickListener {

        boolean onItemLongClicked(RecyclerView recyclerView, int position, View v);
    }
}

Kotlin / Java

also create a file values/ids.xml and put this in it:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="item_click_support" type="id" />
</resources>

How it works

This class works by attaching a RecyclerView.OnChildAttachStateChangeListener to the RecyclerView. This listener is notified every time a child is attached or detached from the RecyclerView. The code use this to append a tap/long click listener to the view. That listener ask the RecyclerView for the RecyclerView.ViewHolder which contains the position.

You could also adapt the code to give you back the holder itself if you need more.

Keep in mind that it's COMPLETELY fine to handle it in your adapter by setting on each view of your list a click listener, like other answer proposed. It's just not the most efficient thing to do (you create a new listener every time you reuse a view) but it works and in most cases it's not an issue.

Why the RecyclerView has no onItemClickListener

The RecyclerView is a toolbox, in contrast of the old ListView it has less build in features and more flexibility. The onItemClickListener is not the only feature being removed from ListView. But it has lot of listeners and method to extend it to your liking, it's far more powerful in the right hands ;).

In my opinion the most complex feature removed in RecyclerView is the Fast Scroll. Most of the other features can be easily re-implemented.

@Baker 2017-05-18 01:21:58

Following up MLProgrammer-CiM's excellent RxJava solution

Consume / Observe clicks

Consumer<String> mClickConsumer = new Consumer<String>() {
        @Override
        public void accept(@NonNull String element) throws Exception {
            Toast.makeText(getApplicationContext(), element +" was clicked", Toast.LENGTH_LONG).show();
        }
    };

ReactiveAdapter rxAdapter = new ReactiveAdapter();
rxAdapter.getPositionClicks().subscribe(mClickConsumer);

RxJava 2.+

Modify the original tl;dr as:

public Observable<String> getPositionClicks(){
    return onClickSubject;
}

PublishSubject#asObservable() was removed. Just return the PublishSubject which is an Observable.

@bluetoothfx 2018-08-18 12:04:30

Where are you getting mClickConsumer on second line, if you please explain a little bit. rxAdapter.getPositionClicks().subscribe(mClickConsumer);

@Alex 2018-04-28 09:21:21

Example with getTag()/setTag() and single click listener for whole adapter:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    String[] mDataset = { "One", "Two", "Three" };

    private final View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Object pos = v.getTag(R.id.TAG_POSITION);
            if(pos instanceof Integer) {
                // here is your position in the dataset that was clicked
                int position = (Integer) pos;

                ...
            }
        }
    };

    class MyViewHolder extends RecyclerView.ViewHolder {
        View mItemView;
        TextView mTextView; // as example
            ...

        MyViewHolder(View itemLayoutView){
            super(itemLayoutView);

            mItemView = itemLayoutView;
            mTextView = itemLayoutView.findViewById(R.id.my_text_view_id);
            ....
            itemLayoutView.setOnClickListener(mClickListener);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter(String[] myDataset) {
        mDataset = myDataset;
    }

    @Override 
    public void onBindViewHolder(final ViewHolder holder, int position) {
        // you could use getTag() here for to get previous position 
        // that used the holder and for example cancel prev async requests 
        // to load images for the old position or so.
        //
        // setTag() new position that use the holder, so then user 
        // will click on the itemView - you will be able to get 
        // the position by getTag()
        holder.mItemView.setTag(R.id.TAG_POSITION, position);

        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        holder.mTextView.setText(mDataset[position]);
    }

    @Override
    public @NonNull MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View item_layout = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.my_recyclerview_item_layout, parent, false);
        ....
        return new MyViewHolder(item_layout);
    }

    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}

The TAG_POSITION defined in tags.xml file as

 <?xml version="1.0" encoding="utf-8"?>
 <resources>
     <item name="TAG_POSITION" type="id"/>
 </resources>

@EpicPandaForce 2018-08-15 23:39:54

RecyclerView doesn't have an onItemClickListener because RecyclerView is responsible for recycling views (surprise!), so it's the responsibility of the view that is recycled to handle the click events it receives.

This actually makes it much easier to use, especially if you had items that can be clicked in multiple places.


Anyways, detecting click on a RecyclerView item is very easy. All you need to do is define an interface (if you're not using Kotlin, in which case you just pass in a lambda):

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
    private final Clicks clicks;

    public MyAdapter(Clicks clicks) {
        this.clicks = clicks;
    }

    private List<MyObject> items = Collections.emptyList();

    public void updateData(List<MyObject> items) {
        this.items = items;
        notifyDataSetChanged(); // TODO: use ListAdapter for diffing instead if you need animations
    }

    public interface Clicks {
        void onItemSelected(MyObject myObject, int position);
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        private MyObject myObject;    

        public MyViewHolder(View view) {
            super(view);
            // bind views
            view.setOnClickListener((v) -> {
                int adapterPosition = getAdapterPosition();
                if(adapterPosition >= 0) {
                    clicks.onItemSelected(myObject, adapterPosition);
                }
            });
        }

        public void bind(MyObject myObject) {
            this.myObject = myObject;
            // bind data to views
        }
    }
}

Same code in Kotlin:

class MyAdapter(val itemClicks: (MyObject, Int) -> Unit): RecyclerView.Adapter<MyViewHolder>() {
    private var items: List<MyObject> = Collections.emptyList()

    fun updateData(items: List<MyObject>) {
        this.items = items
        notifyDataSetChanged() // TODO: use ListAdapter for diffing instead if you need animations
    }

    inner class MyViewHolder(val myView: View): RecyclerView.ViewHolder(myView) {
        private lateinit var myObject: MyObject

        init {
            // binds views
            myView.onClick {
                val adapterPosition = getAdapterPosition()
                if(adapterPosition >= 0) {
                    itemClicks.invoke(myObject, adapterPosition)
                }
            }
        }

        fun bind(myObject: MyObject) {
            this.myObject = myObject
            // bind data to views
        }
    }
}

@Guruprasad 2015-07-23 13:55:40

Android Recyclerview With onItemClickListener, Why we cant try this is working like ListView only.

Source : Link

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

private OnItemClickListener mListener;
public interface OnItemClickListener {
    public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
    mListener = listener;
    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }
    });
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    View childView = view.findChildViewUnder(e.getX(), e.getY());
    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
        mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
    }
    return false;
}

@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

  }
}

And Set this to RecyclerView:

    recyclerView = (RecyclerView)rootView. findViewById(R.id.recyclerView);
    RecyclerView.LayoutManager mLayoutManager = new            LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.addOnItemTouchListener(
            new RecyclerItemClickListener(getActivity(), new   RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    // TODO Handle item click
                    Log.e("@@@@@",""+position);
                }
            })
    );

@vishal dharankar 2016-07-05 18:16:35

No elegant to be honest.

@NickUnuchek 2018-06-11 15:02:56

@vishaldharankar why not? I think that it's the best way to avoid conflict of focus change after using SwipeRefreshLayout

@dave 2017-07-23 07:15:07

Easiest way to do this is as follows:

Declare global variable at start of Adapter class:

// Store out here so we can resuse
private View yourItemView;

Then set the OnClickListener within the onBindViewHolder method:

@Override
public void onBindViewHolder(BusinessAdapter.ViewHolder holder, int position) {

    // Set up the on click listener
    yourItemView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(mContext,Integer.toString(position),Toast.LENGTH_SHORT).show();
        }
    });

}

All other answers are incorrect.

@batsheva 2017-07-27 05:20:20

how do you get the position in OnClick?

@wdina 2017-08-07 07:31:15

You can attach position in tag. yourItemView.setTag(position)

@Embydextrous 2017-08-31 09:05:38

It should be done in onCreateViewHolder method and not onBindViewHolder method. Also, no such comments ('All other answers are lame') on other answers

@dave 2017-10-14 00:30:26

@batsheva - it's already in the onBindViewHolder method. Updated solution.

@dave 2017-10-14 00:33:03

@Embydextrous - why should it be done in onCreateViewHolder? All other answers are lame. None of them address the question and the ones that do require lines and lines of code to do something simple.

@EpicPandaForce 2018-08-15 23:19:08

how do you get the position in OnClick? you use getAdapterPosition()

@user8944115 2017-11-16 03:07:20

recyclerview animation has not been tested, the other is normal. I think it has been optimized to the maximum. Interface has other uses, you can temporarily ignore.

public abstract class BaseAdapterRV<VH extends BaseViewHolder> extends RecyclerView.Adapter<VH> implements AdapterInterface {
    public final String TAG = getClass().getSimpleName();

    protected final Activity mActivity;
    protected final LayoutInflater mInflater;
    protected ItemClickInterface<?, Integer> mListener;

    public BaseAdapterRV(Activity activity) {
        mActivity = activity;
        mInflater = LayoutInflater.from(mActivity);
    }

    @Override
    public final VH onCreateViewHolder(ViewGroup parent, int viewType) {
        return onCreateViewHolder(parent, viewType, mInflater);
    }

    @Override
    public final void onBindViewHolder(VH holder, int position) {
        holder.itemView.setTag(R.id.tag_view_click, position);
        //创建点击事件
        holder.itemView.setOnClickListener(mListener);
        holder.itemView.setOnLongClickListener(mListener);
        onBindVH(holder, position);
    }


    ///////////////////////////////////////////////////////////////////////////
    // 以下是增加的方法
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 注意!涉及到notifyItemInserted刷新时立即获取position可能会不正确
     * 里面也有onItemLongClick
     */
    public void setOnItemClickListener(ItemClickInterface<?, Integer> listener) {
        mListener = listener;
        notifyDataSetChanged();
    }

    @NonNull
    protected abstract VH onCreateViewHolder(ViewGroup parent, int viewType, LayoutInflater inflater);

    protected abstract void onBindVH(VH holder, int position);

}

This is Interface

/**
 * OnItemClickListener的接口
 * 见子类实现{@link OnItemClickListener}{@link OnItemItemClickListener}
 */
public interface ItemClickInterface<DATA1, DATA2> extends View.OnClickListener, View.OnLongClickListener {

    void onItemClick(DATA1 data1, DATA2 data2);

    boolean onItemLongClick(DATA1 data1, DATA2 data2);
}

This is an abstract class

public abstract class OnItemClickListener<DATA> implements ItemClickInterface<View, DATA> {
    @Override
    public void onClick(View v) {
        onItemClick(v, (DATA) v.getTag(R.id.tag_view_click));
    }

    @Override
    public boolean onLongClick(View v) {
        return onItemLongClick(v, (DATA) v.getTag(R.id.tag_view_click));
    }

    @Override
    public boolean onItemLongClick(View view, DATA data) {
        return false;
    }
}

You only need it

    mAdapter.setOnItemClickListener(new OnItemClickListener<Integer>() {
        @Override
        public void onItemClick(View view, Integer integer) {

        }

        @Override
        public boolean onItemLongClick(View view, Integer integer) {
            return true;
        }
    });

@user8944115 2017-11-16 06:29:59

BaseViewHolder as RecyclerView.ViewHolder

@user8944115 2017-11-16 06:35:11

R.id.tag_view_click needs you to declare in the values directory <item type = "id" name = "tag_view_click" />

@dileep krishnan 2017-10-07 10:17:54

 main_recyclerview.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e)
        {
            int position=rv.getChildAdapterPosition(rv.findChildViewUnder(e.getX(),e.getY()));

            switch (position)
            {
                case 0:
                {
                    wifi(position);
                    adapter2.notifyDataSetChanged();
                }
                break;

                case 1:
                {
                    sound(position);
                    adapter2.notifyDataSetChanged();
                }
                break;

                case 2:
                {
                    bluetooth(position);
                    adapter2.notifyDataSetChanged();
                }
                break;


            }
            return true;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e)
        {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    });

@dileep krishnan 2017-10-07 10:18:36

its the right solution for recyclerview

@dileep krishnan 2017-10-07 10:23:44

using this u can get exact results..................

@Shashanth 2017-10-07 10:51:36

The question is "Why doesn't RecyclerView have onItemClickListener()?" NOT "How to implement onItemClickListener() in RecyclerView?" .

@That's Enam 2017-09-06 10:18:32

it worked for me. Hope it will help. Most simplest way.

Inside View Holder

class GeneralViewHolder extends RecyclerView.ViewHolder {
    View cachedView = null;

    public GeneralViewHolder(View itemView) {
        super(itemView);
        cachedView = itemView;
    }

Inside OnBindViewHolder()

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final GeneralViewHolder generalViewHolder = (GeneralViewHolder) holder;
            generalViewHolder.cachedView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, "item Clicked at "+position, Toast.LENGTH_SHORT).show();
                }
            });

And let me know, do you have any question about this solution ?

@Liridon Sadiku 2017-07-18 14:39:19

Access the mainView of rowLayout(cell) for you RecyclerView and in your OnBindViewHolder write this code:

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        Movie movie = moviesList.get(position);
        holder.mainView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("pos " + position);
            }
        });
    }

@Mudassir Khan 2017-02-04 13:48:26

Check this one in which I have implemented all the things with a proper way

RecyclerViewHolder Class

public class RecyclerViewHolder extends RecyclerView.ViewHolder  {

    //view holder is for girdview as we used in the listView
    public ImageView imageView,imageView2;
    public RecyclerViewHolder(View itemView) {
        super(itemView);
        this.imageView=(ImageView)itemView.findViewById(R.id.image);
    }

}

Adapter

public class RecyclerView_Adapter extends RecyclerView.Adapter<RecyclerViewHolder> {

    //RecyclerView will extend to recayclerview Adapter
    private ArrayList<ModelClass> arrayList;
    private Context context;
    private static RecyclerViewClickListener itemListener;
    //constructor of the RecyclerView Adapter
    RecyclerView_Adapter(Context context,ArrayList<ModelClass> arrayList,RecyclerViewClickListener itemListener){
        this.context=context;
        this.arrayList=arrayList;
        this.itemListener=itemListener;
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //this method will inflate the custom layout and return as viewHolder
        LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
        ViewGroup mainGroup=(ViewGroup) layoutInflater.inflate(R.layout.single_item,parent,false);
        RecyclerViewHolder listHolder=new RecyclerViewHolder(mainGroup);

        return listHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, final int position) {

        final ModelClass modelClass=arrayList.get(position);
        //holder
        RecyclerViewHolder mainHolder=(RecyclerViewHolder)holder;
        //convert the drawable image into bitmap
        Bitmap image= BitmapFactory.decodeResource(context.getResources(),modelClass.getImage());
        //set the image into imageView
        mainHolder.imageView.setImageBitmap(image);
        //to handle on click event when clicked on the recyclerview item and
        // get it through the RecyclerViewHolder class we have defined the views there
        mainHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //get the position of the image which is clicked
             itemListener.recyclerViewListClicked(v,position);
            }
        });

    }

    @Override
    public int getItemCount() {
        return (null!=arrayList?arrayList.size():0);
    }
}

The interface

public interface RecyclerViewClickListener {

    //this is method to handle the event when clicked on the image in Recyclerview
    public void recyclerViewListClicked(View v,int position);
}

//and to call this method in activity
RecyclerView_Adapter adapter=new RecyclerView_Adapter(Wallpaper.this,arrayList,this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();


    @Override
    public void  recyclerViewListClicked(View v,int position){

        imageView.setImageResource(wallpaperImages[position]);

    }

@Chathura Jayanath 2017-02-02 11:54:47

I wrote a library to handle android recycler view item click event. You can find whole tutorial in https://github.com/ChathuraHettiarachchi/RecycleClick

RecycleClick.addTo(YOUR_RECYCLEVIEW).setOnItemClickListener(new RecycleClick.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                // YOUR CODE
            }
        });

or to handle item long press you can use

RecycleClick.addTo(YOUR_RECYCLEVIEW).setOnItemLongClickListener(new RecycleClick.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClicked(RecyclerView recyclerView, int position, View v) {
                // YOUR CODE
                return true;
            }
        });

@Abhijeet 2017-05-19 04:52:02

Sir i have tried your library but facing issue with maven?

@Jae-Min Kim 2016-08-26 14:27:38

Modified my comment...

public class MyViewHolder extends RecyclerView.ViewHolder {

        private Context mContext;

        public MyViewHolder(View itemView) {
            super(itemView);

            mContext = itemView.getContext();

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    int itemPosition = getLayoutPosition();
                    Toast.makeText(mContext, "" + itemPosition, Toast.LENGTH_SHORT).show();

                }
            });
        }

@Davideas 2016-10-11 23:14:41

It's a suggestion, but better if you delete this answer, unless many people will vote negatively. This solution is definitively wrong, it works but is bad programming. Please read some blogs for RecyclerView and study some Adapter libraries, there are many valid in Github already, like FlexibleAdapter, FastAdapter and so on...

@Davideas 2016-10-13 07:52:40

You answer is relatively new of a long list of high voted answers and at the bottom of the page, that's why it still has 0 votes. By the way, in the new code, you should use getAdapterPosition().

@Davideas 2016-10-17 22:42:53

You just need to read the javaDoc of the 2 methods.

@Wooff 2015-04-02 08:38:38

How to put it all together example...

  • onClick() handling
  • Cursor - RecyclerView
  • ViewHolder types

    public class OrderListCursorAdapter extends CursorRecyclerViewAdapter<OrderListCursorAdapter.ViewHolder> {
    
    private static final String TAG = OrderListCursorAdapter.class.getSimpleName();
    private static final int ID_VIEW_HOLDER_ACTUAL = 0;
    private static final int ID_VIEW_HOLDER = 1;
    
    public OrderListCursorAdapter(Context context, Cursor cursor) {
        super(context, cursor);
    }
    
    public static class ViewHolderActual extends ViewHolder {
        private static final String TAG = ViewHolderActual.class.getSimpleName();
        protected IViewHolderClick listener;
        protected Button button;
    
        public ViewHolderActual(View v, IViewHolderClick listener) {
            super(v, listener);
            this.listener = listener;
            button = (Button) v.findViewById(R.id.orderList_item_button);
            button.setOnClickListener(this);
        }
    
        public void initFromData(OrderData data) {
            Log.d(TAG, "><initFromData(data=" + data + ")");
            orderId = data.getId();
            vAddressStart.setText(data.getAddressStart());
            vAddressEnd.setText(data.getAddressEnd());
        }
    
        @Override
        public void onClick(View view) {
            if (view instanceof Button) {
                listener.onButtonClick((Button) view, getPosition(), this);
            } else {
                super.onClick(view);
            }
        }
    
        public interface IViewHolderClick extends ViewHolder.IViewHolderClick {
            public void onButtonClick(Button button, int position, ViewHolder viewHolder);
        }
    }
    
    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private static final String TAG = ViewHolder.class.getSimpleName();
        protected long orderId;
        protected IViewHolderClick listener;
        protected TextView vAddressStart;
        protected TextView vAddressEnd;
        protected TextView vStatus;
    
        public ViewHolder(View v, IViewHolderClick listener) {
            super(v);
            this.listener = listener;
            v.setOnClickListener(this);
    
            vAddressStart = (TextView) v.findViewById(R.id.addressStart);
            vAddressEnd = (TextView) v.findViewById(R.id.addressEnd);
            vStatus = (TextView) v.findViewById(R.id.status);
        }
    
        public void initFromData(OrderData data) {
            Log.d(TAG, "><initFromData(data=" + data + ")");
            orderId = data.getId();
            vAddressStart.setText(data.getAddressStart());
            vAddressEnd.setText(data.getAddressEnd());
        }
    
        public long getOrderId() {
            return orderId;
        }
    
        @Override
        public void onClick(View view) {
            listener.onCardClick(view, getPosition(), this);
        }
    
        public interface IViewHolderClick {
            public void onCardClick(View view, int position, ViewHolder viewHolder);
        }
    }
    
    @Override
    public int getItemViewType(int position) {
        return position == 0 ? ID_VIEW_HOLDER_ACTUAL : ID_VIEW_HOLDER;
    }
    
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Log.d(TAG, ">>onCreateViewHolder(parent=" + parent + ", viewType=" + viewType + ")");
    
        ViewHolder result;
    
        switch (viewType) {
            case ID_VIEW_HOLDER_ACTUAL: {
                View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout_actual, parent, false);
                result = new ViewHolderActual(itemView, new ViewHolderActual.IViewHolderClick() {
                    @Override
                    public void onCardClick(View view, int position, ViewHolder viewHolder) {
                        Log.d(TAG, "><onCardClick(view=" + view + ", position=" + position + ", viewHolder=" + viewHolder + ")");
                        Intent intent = new Intent(view.getContext(), OrderDetailActivity.class);
                        intent.putExtra(OrderDetailActivity.ARG_ORDER_ID, viewHolder.getOrderId());
                        view.getContext().startActivity(intent);
                    }
    
                    @Override
                    public void onButtonClick(Button button, int position, ViewHolder viewHolder) {
                        Log.d(TAG, "><onButtonClick(button=" + button + ", position=" + position + ", viewHolder=" + viewHolder + ")");
                        Intent intent = new Intent(button.getContext(), OrderMapActivity.class);
                        intent.putExtra(OrderMapActivity.ARG_ORDER_ID, viewHolder.getOrderId());
                        button.getContext().startActivity(intent);
                    }
                });
                break;
            }
            case ID_VIEW_HOLDER:
            default: {
                View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);
                result = new ViewHolder(itemView, new ViewHolder.IViewHolderClick() {
                    @Override
                    public void onCardClick(View view, int position, ViewHolder viewHolder) {
                        Log.d(TAG, "><onCardClick(view=" + view + ", position=" + position + ", viewHolder=" + viewHolder + ")");
                        Intent intent = new Intent(view.getContext(), OrderDetailActivity.class);
                        intent.putExtra(OrderDetailActivity.ARG_ORDER_ID, viewHolder.getOrderId());
                        view.getContext().startActivity(intent);
                    }
                });
                break;
            }
        }
    
        Log.d(TAG, "<<onCreateViewHolder(parent=" + parent + ", viewType=" + viewType + ")= " + result);
        return result;
    }
    
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, Cursor cursor) {
        Log.d(TAG, "><onBindViewHolder(viewHolder=" + viewHolder + ", cursor=" + cursor + ")");
        final OrderData orderData = new OrderData(cursor);
        viewHolder.initFromData(orderData);
    }
    }
    

@Janishar Ali 2016-08-19 08:43:31

use PlaceHolderView

@Layout(R.layout.item_view_1)
public class View1{

    @View(R.id.txt)
    public TextView txt;

    @Resolve
    public void onResolved() {
        txt.setText(String.valueOf(System.currentTimeMillis() / 1000));
    }

    @Click(R.id.btn)
    public void onClick(){
        txt.setText(String.valueOf(System.currentTimeMillis() / 1000));
    }
}

@Arpit Patel 2016-08-05 13:07:03

Here you can handle multiple onclick see below code and it is very efficient

    public class RVNewsAdapter extends RecyclerView.Adapter<RVNewsAdapter.FeedHolder> {

    private Context context;
    List<News> newsList;
    // Allows to remember the last item shown on screen
    private int lastPosition = -1;

    public RVNewsAdapter(List<News> newsList, Context context) {
        this.newsList = newsList;
        this.context = context;
    }

    public static class FeedHolder extends RecyclerView.ViewHolder implements OnClickListener {

        ImageView img_main;
        TextView tv_title;
        Button bt_facebook, bt_twitter, bt_share, bt_comment;


        public FeedHolder(View itemView) {
            super(itemView);

            img_main = (ImageView) itemView.findViewById(R.id.img_main);
            tv_title = (TextView) itemView.findViewById(R.id.tv_title);
            bt_facebook = (Button) itemView.findViewById(R.id.bt_facebook);
            bt_twitter = (Button) itemView.findViewById(R.id.bt_twitter);
            bt_share = (Button) itemView.findViewById(R.id.bt_share);
            bt_comment = (Button) itemView.findViewById(R.id.bt_comment);

            img_main.setOnClickListener(this);
            bt_facebook.setOnClickListener(this);
            bt_twitter.setOnClickListener(this);
            bt_comment.setOnClickListener(this);
            bt_share.setOnClickListener(this);

        }


        @Override
        public void onClick(View v) {

            if (v.getId() == bt_comment.getId()) {

                Toast.makeText(v.getContext(), "Comment  " , Toast.LENGTH_SHORT).show();

            } else if (v.getId() == bt_facebook.getId()) {

                Toast.makeText(v.getContext(), "Facebook  " , Toast.LENGTH_SHORT).show();

            } else if (v.getId() == bt_twitter.getId()) {

                Toast.makeText(v.getContext(), "Twitter  " , Toast.LENGTH_SHORT).show();

            } else if (v.getId() == bt_share.getId()) {

                Toast.makeText(v.getContext(), "share  " , Toast.LENGTH_SHORT).show();

            }
            else {
                Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public FeedHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_row, parent, false);
        FeedHolder feedHolder = new FeedHolder(view);

        return feedHolder;
    }

    @Override
    public void onBindViewHolder(FeedHolder holder, int position) {

        holder.tv_title.setText(newsList.get(position).getTitle());


        // Here you apply the animation when the view is bound
        setAnimation(holder.img_main, position);
    }

    @Override
    public int getItemCount() {
        return newsList.size();
    }


    /**
     * Here is the key method to apply the animation
     */
    private void setAnimation(View viewToAnimate, int position) {
        // If the bound view wasn't previously displayed on screen, it's animated
        if (position > lastPosition) {
            Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
            viewToAnimate.startAnimation(animation);
            lastPosition = position;
        }
    }


}

@Davideas 2016-10-11 23:16:42

He meant the itemView.

@MLProgrammer-CiM 2014-07-24 12:00:40

tl;dr 2016 Use RxJava and a PublishSubject to expose an Observable for the clicks.

public class ReactiveAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    String[] mDataset = { "Data", "In", "Adapter" };

    private final PublishSubject<String> onClickSubject = PublishSubject.create();

    @Override 
    public void onBindViewHolder(final ViewHolder holder, int position) {
        final String element = mDataset[position];

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               onClickSubject.onNext(element);
            }
        });
    }

    public Observable<String> getPositionClicks(){
        return onClickSubject.asObservable();
    }
}

Original Post:

Since the introduction of ListView, onItemClickListener has been problematic. The moment you have a click listener for any of the internal elements the callback would not be triggered but it wasn't notified or well documented (if at all) so there was a lot of confusion and SO questions about it.

Given that RecyclerView takes it a step further and doesn't have a concept of a row/column, but rather an arbitrarily laid out amount of children, they have delegated the onClick to each one of them, or to programmer implementation.

Think of Recyclerview not as a ListView 1:1 replacement but rather as a more flexible component for complex use cases. And as you say, your solution is what google expected of you. Now you have an adapter who can delegate onClick to an interface passed on the constructor, which is the correct pattern for both ListView and Recyclerview.

public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {

    public TextView txtViewTitle;
    public ImageView imgViewIcon;
    public IMyViewHolderClicks mListener;

    public ViewHolder(View itemLayoutView, IMyViewHolderClicks listener) {
        super(itemLayoutView);
        mListener = listener;
        txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
        imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
        imgViewIcon.setOnClickListener(this);
        itemLayoutView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v instanceof ImageView){
           mListener.onTomato((ImageView)v);
        } else {
           mListener.onPotato(v);
        }
    }

    public static interface IMyViewHolderClicks {
        public void onPotato(View caller);
        public void onTomato(ImageView callerImage);
    }

}

and then on your adapter

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

   String[] mDataset = { "Data" };

   @Override
   public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout, parent, false);

       MyAdapter.ViewHolder vh = new ViewHolder(v, new MyAdapter.ViewHolder.IMyViewHolderClicks() { 
           public void onPotato(View caller) { Log.d("VEGETABLES", "Poh-tah-tos"); };
           public void onTomato(ImageView callerImage) { Log.d("VEGETABLES", "To-m8-tohs"); }
        });
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager) 
    @Override 
    public void onBindViewHolder(ViewHolder holder, int position) {
        // Get element from your dataset at this position 
        // Replace the contents of the view with that element 
        // Clear the ones that won't be used
        holder.txtViewTitle.setText(mDataset[position]);
    } 

    // Return the size of your dataset (invoked by the layout manager) 
    @Override 
    public int getItemCount() { 
        return mDataset.length;
    } 
  ...

Now look into that last piece of code: onCreateViewHolder(ViewGroup parent, int viewType) the signature already suggest different view types. For each one of them you'll require a different viewholder too, and subsequently each one of them can have a different set of clicks. Or you can just create a generic viewholder that takes any view and one onClickListener and applies accordingly. Or delegate up one level to the orchestrator so several fragments/activities have the same list with different click behaviour. Again, all flexibility is on your side.

It is a really needed component and fairly close to what our internal implementations and improvements to ListView were until now. It's good that Google finally acknowledges it.

@se_bastiaan 2014-11-05 20:50:19

RecyclerView.ViewHolder has a getPosition() method. With some adjustments to this code, you can pass the position to the listener.

@MLProgrammer-CiM 2014-11-05 21:19:39

He completely missed the onBindViewHolder(holder, position) , which is where the info is supposed to be filled.

@Kaushik Gopal 2015-01-08 02:45:43

fantastic answer! in addition to showing the solution code-unlike most answers you find on SO for this very same question-this answer explains possible inspiration for what would otherwise seem like a nincompoop move from Google. +1 for use of a smaller class to act as the listener inteface vs passing the whole adapter to act as the interface.

@humblerookie 2015-01-14 12:55:21

Here's a neat difference I suppose if u add a onItemclick listener it seems to act in a single touch manner i.e only one item can be clicked at a time. However if you add clicklisteners to individual children views it seems to be prone to multiple simultaneous touch.

@upenpat 2015-03-18 12:26:34

@se_bastiaan getPosition() is deprecated "This method is deprecated because its meaning is ambiguous due to the async * handling of adapter updates. Please use {@link #getLayoutPosition()} or * {@link #getAdapterPosition()} depending on your use case."

@se_bastiaan 2015-03-18 22:38:52

@upenpat It might be now, it wasn't then.

@upenpat 2015-03-19 11:33:55

@se_bastiaan yes..I meant its deprecated now ..even I used that approach and upvoted :)

@IHeartAndroid 2015-05-07 15:58:41

The advantage of OnItemClickListener was however that the click had an ui effect, i.e. the user sees a click animation on the view. By using the OnClickListener in the ViewHolder, this is not guaranteed any longer. A workaround is to use the following (however works only with API +11) : <android.support.v7.widget.CardView android:layout_width="fill_parent" android:layout_height="wrap_content" android:clickable="true" android:foreground="?android:attr/selectableItemBackground">

@MLProgrammer-CiM 2015-05-07 17:10:14

It's not guaranteed because you have to define it yourself, as a lineal/relative/frame does not have a background selector by default. Put one acknowledging touches and it'll just work.

@Sotti 2015-05-11 12:50:56

Excellent answer, thank you. It's working for me but I have one question. How do you know which row (position) was clicked?? I mean, you are actually clicking an item in the viewHolder, but how do you know what's the position of this viewHolder in the RecyclerView??

@MLProgrammer-CiM 2015-05-11 12:58:08

You have several options. Putting the position in an int field inside the viewholder, update it while binding, then returning it on click is one.

@Randika Vishman 2015-06-24 20:56:18

Out of around 10-15 answers this was the only one which helped me. I don't know if this is the best practice or not, but it did what I wanted and without bugs, where the bugs like that, edited contents of Line items replicated in non-edited/non-touched Line items. However, now I have a question. Where do you suggest to update a database table upon Line item child views like Button clicks? Less say plus/minus button are there for each row? When and where to update the db when user clicks one of them in each row in different different times? Thanks!

@Randika Vishman 2015-06-24 21:08:09

Wonderful, got the answer! We could do it in onCreateViewHolder's our custom ClickListner methods implementation or at ViewHolder's overridden OnClick method in a switch with view.getID()! I think you may suggest the same! Thanks!

@daveztong 2015-06-29 10:34:41

Delegate up one level to the orchestrator so several fragments/activities have the same list with different click behaviour. This is very useful !

@user1446988 2015-07-08 18:14:31

can something like android:onClick="buttonClicked"....public void speechClicked(View v) {} be used with this approach?

@Chad Bingham 2015-07-23 19:55:41

@MLProgrammer-CiM "You have several options. Putting the position in an int field inside the viewholder, update it while binding, then returning it on click is one." The ViewHolder already has this value, and is already set. Just call viewHolder.getPosition();

@user1446988 2015-07-28 19:59:01

@MLProgrammer-CiM Thanks for the answer. I have learned a lot from applying and testing this. I'm using this approach and trying use it from a custom dialog, but Im stuck on something. I was wondering if you could take a look at my question..thanks link to my question

@delive 2015-07-31 15:02:30

Can you put any example full please ?

@MLProgrammer-CiM 2015-07-31 16:33:33

@delive Sure, write the question, put a 100 karma bounty and I'll come and answer it for you.

@rgv 2015-08-20 15:40:37

@MLProgrammer-CiM in another answer the view.OnClicklistener() is being set to the views, in the OnBindViewHolder(), where as you do it in the VIewHolder class. Is the other guy's way, a bad practice, because it is being assigned every time a view is being drawn. [stackoverflow.com/a/28304164/4127441](Here) is the answer if you didn't find my question clear. Thanks!

@MLProgrammer-CiM 2015-08-20 18:31:20

@Raghav either option is okay. His works better for values that change, like position or the Object associated with that position. See how my listeners only send back the view.

@thiagolr 2015-09-03 11:02:47

How can I avoid double selection (pressing two different lines almost at the same time) with this solution?

@Christophe Fondacci 2015-09-28 23:57:10

The main purpose of OnItemClickListener was to have access to the item / position being clicked. Moving the listener to the ViewHolder does not handle that. I think you should clarify that the viewholder has to get access to the dataset and to the currently bound position. I do think the android framework could have handled that (very common) use case.

@MLProgrammer-CiM 2015-09-29 00:06:03

The ViewHolder does not need to know about the dataset, it should only report the position touched to the adapter and let the adapter handle it. Decouples your types by inverting the dependency.

@WALKER 2015-11-02 10:39:01

But onItemLongClick will be more complicated to implement in this way.

@GuillermoMP 2016-02-21 09:22:18

@WALKER not really, you can implemente View.OnLongClickListener in your recycler view, add it to your desired views and add some methods in your inner interface (or create a second inner interface) and pass the clicks same way your are doing with regular clicks

@WALKER 2016-02-22 08:15:31

The downsides, as I have met during development process,listeners will be a mess in RecyclerView, adapters and viewholders. I have encapsulated a new ListView that extends RecyclerView and implemented onItemClick and onItemLongClick functionality. This list view can fulfill many common situation. But when come to complex list item(eg. a button in list item view,and clicking the button or list item itself produces different action), it doesn't work. Anyway, after understanding the work flow, all things seems pretty convenient now.

@Vlad Iancu 2016-05-03 17:13:34

In the implementation you specify "if (v instanceof Imageview) [...]" to differentiate views from each other. But what happens, if, for example, the view holder in your list has multiple image views, and each image view has a different functionality on onClick()? How do you differentiate the views then?

@MLProgrammer-CiM 2016-05-03 17:43:26

Add a different listener per view.

@Sandra 2016-07-12 10:32:43

How can I listen to the clicks in my activity/fragment?

@axierjhtjz 2016-09-08 09:56:52

Hi, great answer. Would be really nice if you could add some example code on how to get that "element" outside the adapter in te RxJava example. Thank you for your answer! :)

@Harsha 2016-10-15 08:20:17

like gmail with long press for single and multiselection and contextual action mode for delete and share android recycelrview sample code

@Harsha 2016-10-17 06:40:37

no thanks am requesting sample links for if possible give code $50 per hour its too cost for any way thank you.

@Harsha 2016-10-17 06:42:16

am fallowing this post grokkingandroid.com/… most of the stuff is implemented but only one item is selected at a time so am looking for multi selection and deselect selecteed items things

@Fndroid 2016-10-24 10:14:29

Why setOnclickListener not call in onCreateViewHolder?

@MLProgrammer-CiM 2016-10-24 12:36:03

It's another approach, then you have to use holder.getAdapterPosition() when forwarding your component.

@MLProgrammer-CiM 2016-10-24 12:37:02

What I got from Google's talk was that the other approach may have race condition issues, and they went out of their way to solve those instead of promoting this one.

@Yankee 2016-12-01 13:08:47

My mDataset is a List of objects, so I modified your code for it, except for the public Observable<String> getPositionClicks(){ return onClickSubject.asObservable(); } part, how can I change it ? Changing Observable<String> to Observable<myClassType>doesn't work . Thanks

@nevi_me 2016-12-04 06:03:35

I've been struggling with figuring out why my TouchInterceptListeners stopped working when I upgraded build tools to 25. The RxJava approach has helped me get rid of a whole lot of code. Thanks!

@Ujju 2016-12-19 15:19:29

@Yankee try Observable<List<myClassType>>

@Ujju 2016-12-19 15:28:40

@MLProgrammer-CiM I think more details about implementing RxJava approach will help a lot more people, please consider adding full sample or link to refer more on this

@Gabe Sechan 2017-01-25 18:51:59

Adding rxJava just for that is horrible bloat and reduces maintainability. There's places RxJava is useful, but using it for click handlers without a VERY good reason is just an unmaintainable mess.

@MLProgrammer-CiM 2017-01-25 19:58:58

The original solution without dependencies is right below it. The tldr is useful if you already use RxJava in your project.

@AndaluZ 2017-03-07 14:26:53

I use Android Studio 2.3 with targetSdk set to 25 in Gradle. But compiler complains about onClickSubject.asObservable(); saying asObservable() cannot be resolved. Does anyone know why? I'm quite experienced in Android development (but don't call myself a specialist).

@dcow 2017-03-30 19:14:18

Sure the tl: w(on't)r; is cool, but it's terrible general advice for copy-paste SO users. Please don't add RxJava to your project just for this, and please seriously consider the overhead and maintainability burden this incurs if you don't actually know what you're doing or can't justify why you'd want RxJava to wrap input event generation. It's a pretty deep stack to dive through just for a callback. It's certainly not a bad idea, but please be careful.

@MLProgrammer-CiM 2017-04-01 02:17:59

I like your italics.

@Baker 2017-05-18 07:47:54

@MLProgrammer-CiM Thx for the great RxJava solution. So much cleaner/simpler. Was about to suggest an edit showing the observer / consumer side, but maybe too verbose / obvious. If you think it's useful, lemme know and I'll add.

@Peter 2017-11-22 15:34:34

why we should use stupid rXJava , if we want just use a stupid itemclicklistener. Who the hell create this stupid recycler view

@Daniele Segato 2017-11-28 10:46:15

I've nothing against using Rx, on the countrary. But creating a new View.OnClickListener for every bind / view you create is highly inefficient, I wish this wasn't the most voted answer / accepted answer. Teach a bad practice to users! Also, Rx is a plus to the problem of handling the click, which is Android only issue.

@niranjan kurambhatti 2018-04-24 07:33:09

how to pass clicked item position??

@Alex 2018-04-26 08:22:32

Worst accepted answer ever on the stackoverflow for android... with so much ppls that upvote it. Highly inefficient. May be I dont understand something, who creating of onclicklistener on every single bind could be a good approach???? It will produce lot of garbage collection operations. RecyclerView was supposed to improve ListView, but such using of RecyclerView make it close to same.

@MLProgrammer-CiM 2018-04-26 22:53:01

Show me on this doll where this answer hurt you. &&& (+.+) \=/ (|_ ~~~ |) |___| / _ \ /_/ _\ /) (_\

@MLProgrammer-CiM 2018-04-26 22:54:28

Now, in all seriousness. Creating 100 lightweight objects per second for a couple of seconds will not trigger GC pressure any way you look at it. Check the profiler and tell me whether I'm wrong.

@MLProgrammer-CiM 2018-04-26 22:58:12

If you still don't believe me, the old solution has a single click listener per view. More efficient.

@Alex 2018-04-28 08:25:58

Your original post was way more efficient solution. So, who you put the onClickSubject.onNext() to onBindViewHolder()?? Who not put it to the holder constructor as it was in the original post?

@Alex 2018-04-28 08:34:57

in case the position is the problem - you always could use view.setTag()/getTag() for example. Store the position in the tag in time of binding, then get the position from the tag in the single clicklistener for the whole adapter.

@Alex 2018-04-28 09:23:24

@EpicPandaForce 2018-08-15 23:15:44

WTF you don't need PublishSubjects just to handle click events, completely unnecessary addition to this post. Although you also don't need 3 levels of interfaces either. Hrmm.

@MLProgrammer-CiM 2018-08-20 22:11:12

@EpicPandaForce thank god the author decided to keep the original solution with just one interface.

@Ashok Reddy M 2016-07-28 06:38:42

Yes you can

public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {

    //inflate the view 

    View view = LayoutInflator.from(parent.getContext()).inflate(R.layout.layoutID,null);

    ViewHolder holder = new ViewHolder(view);

    //here we can set onClicklistener
    view.setOnClickListener(new  View.OnClickListeener(){
        public void onClick(View v)
        {
            //action
        }
    });

return holder;

@Abdulaziz Noor 2015-03-19 10:22:32

I like this way and I'm using it

Inside

public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)

Put

View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_image_and_text, parent, false);
v.setOnClickListener(new MyOnClickListener());

And create this class anywhere you want it

class MyOnClickListener implements View.OnClickListener {
    @Override
    public void onClick(View v) {
       int itemPosition = recyclerView.indexOfChild(v);
       Log.e("Clicked and Position is ",String.valueOf(itemPosition));
    }
}

I've read before that there is a better way but I like this way is easy and not complicated.

@user2968401 2015-04-25 05:18:56

should probably make MyOnClickListener into instance variable, because you'll be creating a new instance of it everytime with the new Keyword

@Qadir Hussain 2015-05-30 23:26:59

recyclerView.getChildPosition(v); is depricated now use recyclerView. indexOfChild(v);

@delive 2015-07-02 15:20:51

This form works, but this method and implements are old ? I think.. if we can work with material desing, we need update this methods not ?

@Simon 2016-03-01 17:46:32

Don't you have issues when scrolling? On my tests the itemPosition seems to depend on views recycling, so it goes wrong compared to my full list in the adapter.

@The_Martian 2016-09-20 07:55:30

This returns 0 index in mine. Can you explain why?

@guo 2016-10-01 02:02:49

How to get recyclerView in MyOnClickListener?

@Arbaz Alam 2017-02-18 06:39:53

Can you please answer this QUESTION

@Daniele Segato 2017-11-28 10:43:25

This is not very efficient. It create an instance of MyOnClickListener for every view, which isn't necessary, and perform a lookup on a view to know the position while you would already have that position if using the actual callback.

@Gordon Freeman 2018-02-20 16:24:34

Instead of using: int itemPosition = recyclerView.indexOfChild(v); you should use: RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(v); int itemPosition = holder.getAdapterPosition();

@mychemicalro 2018-10-01 07:27:53

@guo from the view v, like: recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);

@Shayan_Aryan 2015-04-24 07:58:08

Thanks to @marmor, I updated my answer.

I think it's a good solution to handle the onClick() in the ViewHolder class constructor and pass it to the parent class via OnItemClickListener interface.

MyAdapter.java

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{

private LayoutInflater layoutInflater;
private List<MyObject> items;
private AdapterView.OnItemClickListener onItemClickListener;

public MyAdapter(Context context, AdapterView.OnItemClickListener onItemClickListener, List<MyObject> items) {
    layoutInflater = LayoutInflater.from(context);
    this.items = items;
    this.onItemClickListener = onItemClickListener;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = layoutInflater.inflate(R.layout.my_row_layout, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    MyObject item = items.get(position);
}

public MyObject getItem(int position) {
    return items.get(position);
}


class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    private TextView title;
    private ImageView avatar;

    public ViewHolder(View itemView) {
        super(itemView);
        title = itemView.findViewById(R.id.title);
        avatar = itemView.findViewById(R.id.avatar);

        title.setOnClickListener(this);
        avatar.setOnClickListener(this);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        //passing the clicked position to the parent class
        onItemClickListener.onItemClick(null, view, getAdapterPosition(), view.getId());
    }
}
}

Usage of adapter in other classes:

MyFragment.java

public class MyFragment extends Fragment implements AdapterView.OnItemClickListener {

private RecyclerView recycleview;
private MyAdapter adapter;

    .
    .
    .

private void init(Context context) {
    //passing this fragment as OnItemClickListener to the adapter
    adapter = new MyAdapter(context, this, items);
    recycleview.setAdapter(adapter);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    //you can get the clicked item from the adapter using its position
    MyObject item = adapter.getItem(position);

    //you can also find out which view was clicked
    switch (view.getId()) {
        case R.id.title:
            //title view was clicked
            break;
        case R.id.avatar:
            //avatar view was clicked
            break;
        default:
            //the whole row was clicked
    }
}

}

@marmor 2015-05-13 11:27:06

This will create and garbage-collect tons of objects when scrolling, you should instead create one OnClickListener and re-use it

@vovahost 2015-05-25 20:32:28

Also onBindViewHolder() is called many times for the same view when scrolling. Even creating a single OnClickListener will not help because you will be resetting the OnClickListener every time onBindViewHolder() is called. See instead @MLProgrammer-CiM solution.

@vovahost 2015-05-25 20:40:06

You can also improve @MLProgrammer-CiM solution and instead of creating a listener object for every View in this line MyAdapter.ViewHolder vh = new ViewHolder(v, new MyAdapter.ViewHolder.IMyViewHolderClicks() .... you can create a single listener for all views.

@waqas ali 2016-03-09 12:04:38

Guys use this code in Your main activity. Very Efficient Method

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.users_list);            
UsersAdapter adapter = new UsersAdapter(users, this);
recyclerView.setAdapter(adapter);
adapter.setOnCardClickListner(this);

Here is your Adapter class.

public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UserViewHolder> {
        private ArrayList<User> mDataSet;
        OnCardClickListner onCardClickListner;


        public UsersAdapter(ArrayList<User> mDataSet) {
            this.mDataSet = mDataSet;
        }

        @Override
        public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_row_layout, parent, false);
            UserViewHolder userViewHolder = new UserViewHolder(v);
            return userViewHolder;
        }

        @Override
        public void onBindViewHolder(UserViewHolder holder, final int position) {
            holder.name_entry.setText(mDataSet.get(position).getUser_name());
            holder.cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onCardClickListner.OnCardClicked(v, position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mDataSet.size();
        }

        @Override
        public void onAttachedToRecyclerView(RecyclerView recyclerView) {
            super.onAttachedToRecyclerView(recyclerView);
        }


        public static class UserViewHolder extends RecyclerView.ViewHolder {
            CardView cardView;
            TextView name_entry;

            public UserViewHolder(View itemView) {
                super(itemView);
                cardView = (CardView) itemView.findViewById(R.id.user_layout);
                name_entry = (TextView) itemView.findViewById(R.id.name_entry);
             }
        }

        public interface OnCardClickListner {
            void OnCardClicked(View view, int position);
        }

        public void setOnCardClickListner(OnCardClickListner onCardClickListner) {
            this.onCardClickListner = onCardClickListner;
        }
    }

After this you will get this override method in your activity.

@Override
    public void OnCardClicked(View view, int position) {
        Log.d("OnClick", "Card Position" + position);
    }

@Vinh.TV 2016-06-10 02:54:06

I wonder if user scrolling up & down, OnClickListener will create & be recycle over & over again, it it efficiently?

@waqas ali 2016-06-10 05:07:27

To get the updated position of card, this minor thing can be compromised.

@Harsha 2016-08-30 05:57:32

hi friend nice its working charm,i have a requirement activity with categories and products initially,if user select category icon i need to display categories in dialog box or activity if user select any category based thata load filtered data on to first activity please help me how to solve

@waqas ali 2016-09-01 05:48:52

1st: You need to add a method named OnProductClicked in interface OnCardClickListner like this public interface OnCardClickListner { void OnCardClicked(View view, int position); void OnProductClicked (View view, int position); } 2nd: Then implement click listener on your product icon like this. holder.yourProductIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCardClickListner.OnProductClicked (v, position); } });

@The_Martian 2016-09-20 07:26:21

I am unable to Override OnCardClicked. How are folks upvoting this answer?

@waqas ali 2016-09-20 07:41:35

Implement interface OnCardClickListner then you are gonna get Override OnCardClicked.

@Harsha 2016-10-15 08:23:36

like gmail how to longpress on item to display contextual action mode remove and multiple options for recyclerview single and multi selection modes

@Daniele Segato 2017-11-28 10:40:49

Please avoid creating an object every time you bind like proposed in this solution, it's highly inefficient, scrolling the garbage collector will have to run all the time to get rid of all those View.OnClickListener.

@Jorgesys 2019-07-18 15:11:23

Creating a listener on every onBindViewHolder() call is NOT efficient!

@Simon 2016-03-01 18:25:24

Here is a way to implement it quite easily if you have a list of POJOs and want to retrieve one on click from outside the adapter.

In your adapter, create a listener for the click events and a method to set it:

public class MyAdapter extends RecyclerView.Adapter<SitesListAdapter.ViewHolder> {
...
private List<MyPojo> mMyPojos;
private static OnItemClickListener mOnItemClickListener;

...
public interface OnItemClickListener {
    public void onItemClick(MyPojo pojo);
}

...
public void setOnItemClickListener(OnItemClickListener onItemClickListener){
    mOnItemClickListener = onItemClickListener;
}
...

}

In your ViewHolder, implement onClickListener and create a class member to temporarily store the POJO the view is presenting, that way (this is an example, creating a setter would be better):

public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public MyPojo mCurrentPojo;
    ...
    public ViewHolder(View view) {
        super(v);
        ...
        view.setOnClickListener(this); //You could set this on part of the layout too
    }

    ...
    @Override
    public void onClick(View view) {
        if(mOnItemClickListener != null && mCurrentPojo != null){
            mOnItemClickListener.onItemClick(mCurrentPojo);
        }
    }

Back in your adapter, set the current POJO when the ViewHolder is bound (or to null if the current view doesn't have one):

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    final MyPojo currentPojo = mMyPojos.get(position); 
    holder.mCurrentPojo = currentPojo;
    ...

That's it, now you can use it like this from your fragment/activity:

    mMyAdapter.setOnItemClickListener(new mMyAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(MyPojo pojo) {
            //Do whatever you want with your pojo here
        }
    });

@Akshay 2016-11-22 19:38:24

you are trying to implement Interface as if it would be an Object method. This won't work

@Akshay 2016-11-22 21:02:47

Update : What you need is mMyAdapter.setOnItemClickListener(MyAdapter.OnItemClickListe‌​ner() {});

@Simon 2016-11-23 11:52:22

@Akshay Sorry but I think my code is correct. Did you try it? All the listeners on Android follow the same principle, and you need to instantiate the interface with a 'new' (ex: stackoverflow.com/questions/4709870/…)

@Hiren Patel 2016-02-03 13:44:31

I have done this way, its very simple:

Just add 1 Line for Clicked RecyclerView position:

int position = getLayoutPosition()

Full code for ViewHolder class:

private class ChildViewHolder extends RecyclerView.ViewHolder {
        public ImageView imageView;
        public TextView txtView;

        public ChildViewHolder(View itemView) {
            super(itemView);
            imageView= (ImageView)itemView.findViewById(R.id.imageView);
            txtView= (TextView) itemView.findViewById(R.id.txtView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.i("RecyclerView Item Click Position", String.valueOf(getLayoutPosition()));
                }
            });
        }
    }

Hope this will help you.

@Naren 2015-12-27 00:54:10

This worked for me:

@Override
public void onBindViewHolder(PlacesListViewAdapter.ViewHolder holder, int position) {
    ----
    ----
    ----
    // Set setOnClickListener(holder);
}


@Override
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    ----
    ----
    ----

    @Override
    public void onClick(View view) {
        // Use to get the item clicked getAdapterPosition()
    }
}

@Alex Kisel 2017-12-29 20:53:21

It isn't good way setting setOnClickListener(holder) in onBindViewHolder(). Because onBindViewHolder(...) isn't called after notify() methods. So, you can get wrong click position in some situations.

@cryyyyy 2015-11-30 12:46:20

If you want to add onClick() to the child view of items, for example, a button in item, I found that you can do it easily in onCreateViewHolder() of your own RecyclerView.Adapter just like this:

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater
                    .from(parent.getContext())
                    .inflate(R.layout.cell, null);

            Button btn = (Button) v.findViewById(R.id.btn);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //do it
                }
            });

            return new MyViewHolder(v);
        }

i don't know whether it's a good way, but it works well. If anyone has a better idea, very glad to tell me and correct my answer! :)

@Alexandru Circus 2015-11-28 13:09:28

See my approach on this:

First declare an interface like this:

/**
 * Interface used for delegating item click events in a {@link android.support.v7.widget.RecyclerView}
 * Created by Alex on 11/28/2015.
 */
  public interface OnRecyclerItemClickListener<T> {

     /**
      * Called when a click occurred inside a recyclerView item view
      * @param view that was clicked
      * @param position of the clicked view
      * @param item the concrete data that is displayed through the clicked view
      */
      void onItemClick(View view, int position, T item);
   }

Then create the adapter:

public class CustomRecyclerAdapter extends RecyclerView.Adapter {      

    private class InternalClickListener implements View.OnClickListener{

      @Override
      public void onClick(View v) {
        if(mRecyclerView != null && mItemClickListener != null){
            // find the position of the item that was clicked
            int position = mRecyclerView.getChildAdapterPosition(v);
            Data data = getItem(position);
            // notify the main listener
            mItemClickListener.onItemClick(v, position, data);
        }
    }
}

private final OnRecyclerItemClickListener mItemClickListener;
private RecyclerView mRecyclerView;    
private InternalClickListener mInternalClickListener;


/**
 *
 * @param itemClickListener used to trigger an item click event
 */
public PlayerListRecyclerAdapter(OnRecyclerItemClickListener itemClickListener){        
    mItemClickListener = itemClickListener;
    mInternalClickListener = new InternalClickListener();
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
   View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);

    v.setOnClickListener(mInternalClickListener);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    // do your binding here
}

@Override
public int getItemCount() {
    return mDataSet.size();
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);

    mRecyclerView = recyclerView;
}

@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
    super.onDetachedFromRecyclerView(recyclerView);

    mRecyclerView = null;
}

public Data getItem(int position){
    return mDataset.get(position);
}
}

And now let's see how to integrate this from a fragment:

public class TestFragment extends Fragment implements OnRecyclerItemClickListener<Data>{
   private RecyclerView mRecyclerView;

   @Override
   public void onItemClick(View view, int position, Data item) {
     // do something
   }

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      return inflater.inflate(R.layout.test_fragment, container, false);
   }

   @Override
   public void onViewCreated(View view, Bundle savedInstanceState) {
      mRecyclerView = view.findViewById(idOfTheRecycler);
      mRecyclerView .setAdapter(new CustomRecyclerAdapter(this));
   }

@Manikanta 2015-10-07 06:38:43

Instead of implementing interface View.OnClickListener inside view holder or creating and interface and implementing interface in your activity.. I used this code for simple on OnClickListener implementation.

public static class SimpleStringRecyclerViewAdapter
            extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> {

        // Your initializations goes here...
        private List<String> mValues;

        public static class ViewHolder extends RecyclerView.ViewHolder {

            //create a variable mView
            public final View mView;

            /*All your row widgets goes here
            public final ImageView mImageView;
            public final TextView mTextView;*/

            public ViewHolder(View view) {
                super(view);
                //Initialize it here
                mView = view;

                /* your row widgets initializations goes here
                mImageView = (ImageView) view.findViewById(R.id.avatar);
                mTextView = (TextView) view.findViewById(android.R.id.text1);*/
            }
        }

        public String getValueAt(int position) {
            return mValues.get(position);
        }

        public SimpleStringRecyclerViewAdapter(Context context, List<String> items) {

            mBackground = mTypedValue.resourceId;
            mValues = items;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_item, parent, false);
            view.setBackgroundResource(mBackground);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            holder.mBoundString = mValues.get(position);
            holder.mTextView.setText(mValues.get(position));

            //Here it is simply write onItemClick listener here
            holder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Context context = v.getContext();
                    Intent intent = new Intent(context, ExampleActivity.class);

                    context.startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mValues.size();
        }
    }

@Alexandru Circus 2015-11-27 22:56:34

And you think creating a new OnItemClickListener object at each onBind() method call is a good approach?

@sam 2019-02-28 11:55:07

Good job. Works great!

@chad 2015-08-12 08:07:32

After reading @MLProgrammer-CiM's answer, here is my code:

class NormalViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    @Bind(R.id.card_item_normal)
    CardView cardView;

    public NormalViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
        cardView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v instanceof CardView) {
            // use getAdapterPosition() instead of getLayoutPosition()
            int itemPosition = getAdapterPosition();
            removeItem(itemPosition);
        }
    }
}

@Tomasz Mularczyk 2015-06-22 09:54:14

As far as I understand MLProgrammer-CiM answer, simply it's possible to just do this:

class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    private ImageView image;
    private TextView title;
    private TextView price;

    public MyViewHolder(View itemView) {
        super(itemView);
        image = (ImageView)itemView.findViewById(R.id.horizontal_list_image);
        title = (TextView)itemView.findViewById(R.id.horizontal_list_title);
        price = (TextView)itemView.findViewById(R.id.horizontal_list_price);
        image.setOnClickListener(this);
        title.setOnClickListener(this);
        price.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        Toast.makeText(context, "Item click nr: "+getLayoutPosition(), Toast.LENGTH_SHORT).show();
    }
}

@tmac12 2015-06-06 17:54:10

I use this method to start an Intent from RecyclerView:

@Override
 public void onBindViewHolder(ViewHolder viewHolder, int i) {

    final MyClass myClass = mList.get(i);
    viewHolder.txtViewTitle.setText(myclass.name);
   ...
    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
      @Override
       public void onClick(View v){
             Intent detailIntent = new Intent(mContext, type.class);                                                            
             detailIntent.putExtra("MyClass", myclass);
             mContext.startActivity(detailIntent);
       }
}
);

@Alex Kisel 2017-12-29 20:50:01

It isn't good way. Because onBindViewHolder(...) isn't called after notify() methods. So, you can get wrong click position in some situations.

Related Questions

Sponsored Content

25 Answered Questions

10 Answered Questions

[SOLVED] Why is subtracting these two times (in 1927) is giving a strange result?

  • 2011-07-27 08:15:58
  • Freewind
  • 629258 View
  • 6600 Score
  • 10 Answer
  • Tags:   java date timezone

39 Answered Questions

[SOLVED] How to add dividers and spaces between items in RecyclerView?

24 Answered Questions

[SOLVED] What is a serialVersionUID and why should I use it?

3 Answered Questions

[SOLVED] Why is printing "B" dramatically slower than printing "#"?

11 Answered Questions

13 Answered Questions

[SOLVED] Why does Java have transient fields?

  • 2009-05-26 12:11:36
  • Animesh
  • 667792 View
  • 1398 Score
  • 13 Answer
  • Tags:   java field transient

77 Answered Questions

16 Answered Questions

[SOLVED] Why is char[] preferred over String for passwords?

1 Answered Questions

[SOLVED] Swipe and OnClick events in RecyclerView

Sponsored Content