Sarvesh Sarvesh - 1 year ago 91
Android Question

onclicklistener on the specific item of the recyclerview in android

I am going to ask very basic question, but i am stuck in it for a long time.

after card view there is an recycleview which has 2 images in each row.
now i want to create the click listener on the images rather than the recycleview.

the corresponding layout(layout_main.xml) of this activity( contain only recyclerview. the elements of each row is in another layout(layout_images.xml). i am getting the images from layout_images.xml and inflate them in the adapter class(

now how to put action listener on the images only.

secondly, i want to get the image on which i clicked. how to get that.
like, when we click on a view we create some method as

public void onClick(View view){
// some code here

where view is the object on which we clicked. in my case how to get the image on which i clicked.
using type cast it might be throw an exception when user doesnot click on image.

Answer Source

Multiple onClick events inside a recyclerView:

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{

            public ImageView iconImageView;
            public TextView iconTextView;

            public MyViewHolder(final View itemView) {

                iconImageView = (ImageView) itemView.findViewById(;
                iconTextView = (TextView) itemView.findViewById(;
    // set click event
// set long click event

            // onClick Listener for view
            public void onClick(View v) {

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

            //onLongClickListener for view
            public boolean onLongClick(View v) {

                final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setTitle ("Hello Dialog")
                        .setMessage ("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {


                return true;

To get which item was clicked you match the view id i.e. v.getId() == yourViewItem.getId()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download