Reputation: 13
I wan to attach an OnClickListener to a CardView, so i can get the ID from the card
I have a RecyclerView that has a custom adapter for displaying the cards. This is how it's implemented.
I tried other examples in stackoverflow but it didn't work .
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private ArrayList<Patient> patients;
Context mContext;
String idPatient;
public CardAdapter(ArrayList<Patient> patients) {
this.patients = patients;
}
@Override
public CardAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_card_view, viewGroup, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(CardAdapter.ViewHolder viewHolder, int i) {
viewHolder.first_name.setText(patients.get(i).getFirstName());
viewHolder.last_name.setText(patients.get(i).getLastName());
viewHolder.id_patient.setText(String.valueOf(patients.get(i).getId()));
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//trying to get ID From card
ViewGroup parentView = (ViewGroup)v.getParent();
TextView idpatientview =(TextView)parentView.findViewById(R.id.idViewPatient);
idPatient = idpatientview.getText().toString();
PreferencesHelper.save(mContext, "idPatient", idPatient);
Intent intent = new Intent(mContext, BluetoothActivity.class);
mContext.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return patients.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView first_name,last_name,id_patient;
public ViewHolder(View view) {
super(view);
first_name = (TextView)view.findViewById(R.id.textViewName);
last_name = (TextView)view.findViewById(R.id.textViewLastName);
id_patient = (TextView)view.findViewById(R.id.idViewPatient);
}
}
}
Upvotes: 1
Views: 1205
Reputation: 1710
If your onClick method is inside your onBindViewHolder, then you can get the current data directly
String first_name = patients.get(i).getFirstName();
String last_name = patients.get(i).getLastName();
String id_patient = String.valueOf(patients.get(i).getId());
in your onClickListener, the id of the patient corresponding to the clicked card is simply id_patient
, the first name is first_name
and the last name is last_name
. You can now pass the data to your activity (with an interface for exemple)
Upvotes: 2