0

I have an xml file for a cardview to be used in a recyclerview in my main android class. This cardview contains a button that will be used to delete the cardview from the list. The problem I have encountered is that all of the buttons in the recyclerview have identical onClick values and I do not know how to differentiate between them.

Here is my button in the cardview xml:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Delete"
    android:id="@+id/btnDelete"
    android:onClick="DeleteCard"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

In my main class, I have a function DeleteCard which runs whenever I press any of the delete buttons. I have a TextView in my cardview as well, and I was wondering if it was possible to somehow retrieve the text that is in the TextView when I press the delete button so I know which one to delete.

This is my onBindViewHolder:

public void onBindViewHolder(TimeViewHolder personViewHolder, int i) {
    int min = (int)(times.get(i).time / (60 * 1000));
    int remaining = (int)(times.get(i).time % (60 * 1000));
    int sec = remaining / 1000;
    remaining = remaining % (1000);
    int mill = (remaining%1000)/10;
    DecimalFormat df = new DecimalFormat("00");
    personViewHolder.time.setText(min + ":" + df.format(sec) + "." + mill);
    personViewHolder.date.setText(times.get(i).date);
}

I want to get the text from date and use that as a parameter to remove that key in the SharedPreferences. Here is the method that runs when a delete button is pressed:

public void DeleteCard(View view){
    SharedPreferences.Editor editor = history.edit();
    editor.remove("Date Here");
    editor.commit();
}

3 Answers3

0

Implement onclick on Button in onBindViewHolder not in xml and add a tag of position or unique identifier to this button. So when you will click then inside onclick extract tag from view object and perfrom operation which you want.

d.k.
  • 415
  • 4
  • 16
0

The view is passed to the DeleteCard method, so you can get the id of the view using view.getId() and then you can switch the id like this:

 public void DeleteCard(View view) {
    switch(view.getId()){

        case R.id.buttonDelete:
        ....
        break;

        case R.id.buttonAdd:
        ...
        break;



    }
}
dsharew
  • 10,377
  • 6
  • 49
  • 75
0

Remove onClick() from the XML, and add the click listener in the onCreateViewHolder(..) method. The position can be retrieved from the getPosition() method in the ViewHolder class which is deprecated now.

You can get the position using the getAdapterPosition() or getLayoutPosition().

https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#getPosition()

sr09
  • 720
  • 5
  • 26