我是Android开发的新手,我有以下项目结构:
我想从我的activity_category_list
班开始我的StoreViewHolder
。也就是说,只要单击持有者中的视图,就应该开始类别活动。
这是我的 StoreViewHolder.java 来实现这一目标:
public class StoreViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtStoreName;
public ImageView imageView;
private ItemClickListener itemClickListener;
public StoreViewHolder(View itemView) {
super(itemView);
txtStoreName = (TextView) itemView.findViewById(R.id.store_name);
imageView = (ImageView) itemView.findViewById(R.id.store_image);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
@Override
public void onClick(View view) {
itemClickListener.onClick(view, getAdapterPosition(), false);
Intent categoryList = new Intent(view.getContext(), CategoryList.class);
this.startActivity(categoryList); // does not compile here
}
}
我在评论部分得到了标题错误。我试过网上看过的各种方法,但不知怎的,都没用。或者我也试过这个,但没有运气:
Intent categoryList = new Intent(StoreViewHolder.this, CategoryList.class);
startActivity(categoryList);
有什么想法吗?
答案 0 :(得分:0)
要致电startActivity(intent)
,您需要context
。因为startActivity(intent)
方法来自Context类。在Activity
中,您不要像context.startActivity(intent);
那样写,因为Activity
自Context
Acitivty
Context
延伸Context
。在构造函数中传递context.startActivity(intent);
并调用public class StoreViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtStoreName;
public ImageView imageView;
Context context;
private ItemClickListener itemClickListener;
public StoreViewHolder(View itemView, Context context) {
super(itemView);
this.context = context;
txtStoreName = (TextView) itemView.findViewById(R.id.store_name);
imageView = (ImageView) itemView.findViewById(R.id.store_image);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
@Override
public void onClick(View view) {
itemClickListener.onClick(view, getAdapterPosition(), false);
Intent categoryList = new Intent(view.getContext(), CategoryList.class);
context.startActivity(categoryList); // does not compile here
}
}
from:
类似问题Calling startActivity() from outside of an Activity context