我将上下文传递给recyclerview适配器时遇到问题,请参阅下面的代码。我应该如何在Onclick中使Toast工作?
我也有从这个Onclick
开始新活动的问题 Intent intent = new Intent(context, Main2Activity.class);
startActivity(intent);
因为startActivity不被识别为方法。有什么建议吗?
我的代码:
公共类MoviesAdapter扩展了RecyclerView.Adapter {
private List<Movie> moviesList;
private static final String TAG = "MyTestAppState";
Context context;
public MoviesAdapter(Context context, List<Movie> moviesList) {
this.context = context;
this.moviesList = moviesList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, year, genre;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.TXtitle);
genre = (TextView) view.findViewById(R.id.TXgenre);
year = (TextView) view.findViewById(R.id.TXyear);
}
}
public MoviesAdapter(List<Movie> moviesList) {
this.moviesList = moviesList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.movie_list_row, parent, false);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context,"Test", Toast.LENGTH_SHORT).show();
Log.v(TAG, "TEST");
}
});
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
Movie movie = moviesList.get(position);
holder.title.setText(movie.getTitle());
holder.genre.setText(movie.getGenre());
holder.year.setText(movie.getYear());
}
@Override
public int getItemCount() {return moviesList.size();
}
}
答案 0 :(得分:1)
使用context.startActivity(intent);
代替startActivity(intent);
答案 1 :(得分:0)
尝试
context.startActivity(intent);
确保在 AndroidManifest.xml
中添加 Main2Activity