Add clickListner for button inside a cardView populated using a recyclerView

Define your onClick listener on onBindViewHolder method in CustomAdapter.


Add click listener for button inside a cardView populated using a recyclerView

Add click event to buttons which is in RecyclerView as:

1. Get Button from xml in same way as doing for TextView in MyViewHolder class:

public static class MyViewHolder extends RecyclerView.ViewHolder{
    TextView textView;
    Button btnButton1;
    MyViewHolder(View view){
        super(view);
        this.textView= (TextView) view.findViewById(R.id.card_text);
        this.btnButton1= (Button) view.findViewById(R.id.button1);
        ... do same for other Button
    }
}

2. Add setOnClickListener method for Button in onBindViewHolder method:

@Override
public void onBindViewHolder(MyViewHolder myViewHolder, int i){
     myViewHolder.textView.setText(list.get(i));
      myViewHolder.btnButton1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            /// button click event
        }
    });
}

Let's say you have:

<android.support.v7.widget.CardView
    android:id="@+id/cv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="4dp"
    android:elevation="4dp"
    app:cardCornerRadius="2dp">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="16dp">

        <TextView
            android:id="@+id/listText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:padding="8dp"
            android:text="New Text" />

        <ImageButton
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/listText"
            android:layout_alignParentRight="true"
            android:onClick="onClickBotonBorrar"
            android:background="?android:selectableItemBackground"
            android:src="@drawable/ic_action_borrar" />
    </RelativeLayout>

</android.support.v7.widget.CardView>

Note this part: android:onClick="onClickBotonBorrar"

On your Activity add this:

public void onClickBotonBorrar (View v) {
//Do whatever you want when user clicks on your ImageButton
    }

It is recommended not to have the click event inside your adapter but inside your activity.

Note: It's similar for button