我在这里发现了一堆类似的问题,它们大多指向相同的解决方案,但对我而言仍然失败。
基本上,我想使用RecyclerView的项目的onClick启动第二个活动。但是构建失败,因为编译器无法解析RecipeViewHolder的onClick中的startActivity方法。
public class RecipeListAdapter extends
RecyclerView.Adapter<RecipeListAdapter.RecipeViewHolder> {
private final LinkedList<Recipe> mRecipeList;
private LayoutInflater mInflater;
class RecipeViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public final TextView titleView, descView;
final RecipeListAdapter mAdapter;
private Context context;
public RecipeViewHolder(View itemView, RecipeListAdapter adapter){
super(itemView);
this.context = itemView.getContext();
titleView = itemView.findViewById(R.id.name);
descView = itemView.findViewById(R.id.desc);
this.mAdapter = adapter;
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// Get the position of the item that was clicked.
int mPosition = getLayoutPosition();
// Use that to access the affected item in mWordList.
Recipe element = mRecipeList.get(mPosition);
Intent intent = new Intent(context, Details.class);
// TODO: Change to Desc Later
intent.putExtra("Recipe Desc", element.getName());
context.startActvity(intent);
}
}
public RecipeListAdapter(Context context,
LinkedList<Recipe> recipeList){
// this.context = context;
mInflater = LayoutInflater.from(context);
this.mRecipeList = recipeList;
}
@NonNull
@Override
public RecipeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View mItemView = mInflater.inflate(R.layout.recipelist_item, parent, false);
return new RecipeViewHolder(mItemView, this);
}
@Override
public void onBindViewHolder(@NonNull RecipeViewHolder holder, int position) {
Recipe mCurrent = mRecipeList.get(position);
holder.titleView.setText(mCurrent.getName());
holder.descView.setText(mCurrent.getDesc());
}
@Override
public int getItemCount() {
return mRecipeList.size();
}
}
您的拼写错误。您的代码:
@Override
public void onClick(View v) {
// Get the position of the item that was clicked.
int mPosition = getLayoutPosition();
// Use that to access the affected item in mWordList.
Recipe element = mRecipeList.get(mPosition);
Intent intent = new Intent(context, Details.class);
// TODO: Change to Desc Later
intent.putExtra("Recipe Desc", element.getName());
context.startActvity(intent); // wrong spelling
}
和正确的拼写:
context.startActivity(intent);
请注意,并喜欢编码:)