我可以在 onClick
事件中显示一个 Toast
但无法加载新的 Activity
。
这是我的代码:
public class AppointmentAdapter extends RecyclerView.Adapter<AppointmentAdapter.MyViewHolder> {
private ArrayList<Appointment> appointmentList;
private Context mContext;
public AppointmentAdapter(Context context) {
mContext = context;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public Button mView, mSend;
public MyViewHolder(View view) {
super(view);
mView = (Button) view.findViewById(R.id.button_view_appointment);
mSend = (Button) view.findViewById(R.id.button_send_appointment);
mView.setOnClickListener(this);
mSend.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == mView.getId()) {
// Toast.makeText(v.getContext(), "View ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
Intent detailsIntent = new Intent(mContext, DetailsActivity.class);
mContext.startActivity(detailsIntent);
}
if (v.getId() == mSend.getId()) {
// Toast.makeText(v.getContext(), "Send ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
}
/................./
}
这行特定的代码不起作用。
Intent detailsIntent = new Intent(mContext, DetailsActivity.class);
mContext.startActivity(detailsIntent);
}
当我运行这个应用程序时得到了 NullPointException
请帮忙。提前致谢
最佳答案
您的 mContext
变量是 null
。您需要检查您的代码以了解为什么此变量为 null
。
既然您说过可以显示 Toast
,请使用 v.getContext()
。要传递数据,请使用 getAdapterPosition()
获取点击的项目并在 Intent
中传递数据。确保 Appointment
类实现了 Serializable
接口(interface)。
Appointment selectedAppointment = appointmentList.get(getAdapterPosition());
Intent detailsIntent = new Intent(v.getContext(), DetailsActivity.class);
detailsIntent.putExtra("selectedAppointment", selectedAppointment);
v.getContext().startActivity(detailsIntent);
关于android: 无法从 RecyclerView.ViewHolder 加载新 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39695792/