将OnClickListner添加到CardView并获取数据

时间:2016-04-25 15:01:07

标签: android android-recyclerview android-cardview

我想将一个OnClickListener附加到CardView,这样我就可以从卡中获取ID

我有一个RecyclerView,它有一个用于显示卡片的自定义适配器。这就是它的实现方式。

我在stackoverflow中尝试了其他示例,但它没有用。

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);

   }
        }
               }

1 个答案:

答案 0 :(得分:2)

如果您的onClick方法在您的onBindViewHolder中,那么您可以直接获取当前数据

String first_name = patients.get(i).getFirstName();
String last_name = patients.get(i).getLastName();
String id_patient = String.valueOf(patients.get(i).getId());

在您的onClickListener中,与所点击的卡片相对应的患者ID仅为id_patient,名字为first_name,姓氏为last_name。您现在可以将数据传递给您的活动(带有示例界面)