1 year ago
#388663
Emma.bk
Recyclerview opens different Activities with OnClick
This is the first time that I work with a RecyclerView, I can display a Toast
for each item but I can't seem to get the getAbsoluteAdapterPosition()
in my onBindViewHolder
to get the position of my items so that I can make a switch to open a different Activity for each of them.
MyMovieAdapter.java
public class MyMovieAdapter extends RecyclerView.Adapter<MyMovieAdapter.ViewHolder> {
MyMovieData[] myMovieData;
Context context;
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
final MyMovieData myMovieDataList = myMovieData[position];
holder.textViewName.setText(myMovieDataList.getMovieName());
holder.textViewDate.setText(myMovieDataList.getMovieDate());
holder.movieImage.setImageResource(myMovieDataList.getMovieImage());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, myMovieDataList.getMovieName(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "position = " + holder.getAbsoluteAdapterPosition());
final Intent intent;
switch (getAbsoluteAdapterPosition()){
case 0:
intent = new Intent(context, Activity1.class);
break;
case 1:
intent = new Intent(context, Activity2.class);
break;
default:
intent = new Intent(context, Activity3.class);
break;
}
context.startActivity(intent);
}
});
}
I tried putting the OnClick in the MainActivity like that :
public void onItemClick(View view, int position) {
Context context=view.getContext();
Intent intent= new Intent();
switch (position){
case 0:
intent = new Intent(context, Activity1.class);
context.startActivity(intent);
break;
}
}
But it doesn't work either. Any idea what I am doing wrong ?
Answer: I forgot to put holder.
before my getAbsoluteAdapterPosition()
.
java
android
android-studio
android-recyclerview
onclicklistener
0 Answers
Your Answer