android:无法从RecyclerView.ViewHolder加载新活动

时间:2016-09-26 06:12:04

标签: android android-recyclerview onclicklistener

我可以在Toast事件中显示onClick,但无法加载新的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 请帮忙。在此先感谢

3 个答案:

答案 0 :(得分:0)

@sohanoor你甚至可以尝试在onBindViewHolder中生成点击。希望这可以帮助你..

@Override

       <dependency>
            <groupId>com.test.rtc.utils</groupId>
            <artifactId>com.test.rtc.utils.pamaintenance</artifactId>
            <version>${version}</version>
            <exclusions>    
              <exclusion>
              <groupId>com.test.libs</groupId>
              <artifactId>com.ibm.team.*</artifactId>
              </exclusion> 
            </exclusions>
       </dependency>

答案 1 :(得分:0)

您的mContext变量为null。您需要检查代码以查看此变量为null的原因。

由于您说您可以展示Toast使用v.getContext()。要传递数据,请使用getAdapterPosition()点击项目并传递Intent中的数据。确保Appointment类实现Serializable接口。

Appointment selectedAppointment = appointmentList.get(getAdapterPosition());
Intent detailsIntent = new Intent(v.getContext(), DetailsActivity.class);
detailsIntent.putExtra("selectedAppointment", selectedAppointment);
v.getContext().startActivity(detailsIntent);

答案 2 :(得分:0)

查看mView.setonclicklistner

的view.setonclickListner