我试图将单击监听器添加到在适配器类和我正在使用.this关键字关注的教程中创建的图像保持器,但是我需要引用适配器类中的活动?我将附上截图以使其更清晰

Toast.makeText(JudgeActivity.this,post_key,Toast.LENGTH_LONG).show();

这是导致错误的行,(JudgeActivity.this不是一个封闭的类)

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<UploadClass> mUploads;



public ImageAdapter(Context context, List<UploadClass> uploads){
    mContext = context;
    mUploads = uploads;
}

@Override
public  ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
    return new ImageViewHolder(v);
}

@Override
public void onBindViewHolder(ImageViewHolder holder, int position) {

    final String post_key = mUploads.get(position).toString();
    UploadClass uploadCurrent = mUploads.get(position);
    holder.textViewName.setText(uploadCurrent.getName());
    Picasso.with(mContext)
            .load(uploadCurrent.getImageUrl())
            .placeholder(R.mipmap.ic_launcher)
            .fit()
            .centerCrop()
            .into(holder.imageView);

    holder.imageView.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            Toast.makeText(JudgeActivity.this, post_key, Toast.LENGTH_LONG).show();
        }
    });

}


ScreenShot of Code

最佳答案

您需要提供Context实例。我可以看到您的适配器在构造时将具有此实例。从活动或片段中调用new ImageAdapter(Context context, List<UploadClass> uploads)时,会将Context对象(在本例中为Activiy)传递给ImageAdapter实例,以便可以在方法中使用它。

因此,正确的替换将是:

Toast.makeText(mContext, post_key, Toast.LENGTH_LONG).show();


附言如果适配器是JudgeActivity的内部类,则您的代码仍然可以使用。如果您没有将ImageAdapter类与JudgeActivity类分开,则引用JudgeActivity.this上下文应该已经成功。

09-11 18:31