How to implement a transition to another activity by clicking on the item recyclerview ? I added an adapter to the class:

  class MyClickListener implements View.OnClickListener { private Recept recept; @Override public void onClick(View v) { } void setRecord(Recept recept) { this.recept = recept; } } 

But this design does not allow me to create intentions for the transition. How to implement the transition?

  • Why does not allow? No context? - YungBlade
  • @YungBlade; I can't use such code as Intent i = new Intent(Main2Activity.this,LastActivity.class); In its class adapter - Vlad Yulin
  • In onClick, try Intent i = new Intent (view.getContext (), LastActivity.class); - YungBlade
  • @YungBlade Thank you! - Vlad Yulin

2 answers 2

You can try this:

 public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener { private Context mContext; public MyAdapter(Context context) { mContext = context; } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { holder.yourView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(mContext, YourActivity.class); mContext.startActivity(intent); } }); 

    In short, as I understand it, you do not know where to get an instance of the context for the intent constructor. This can be done like this:

    1. Pass an instance of the context in the adapter class constructor, as suggested by Shevchyk Vitalii.
    2. Get context from view, as I wrote.

    Keep in mind that it is not recommended to store an instance of the context in a variable, because it is fraught with memory leaks, it is better to get it from somewhere.