无法从适配器向活动添加功能

时间:2019-01-10 17:40:52

标签: java

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

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

这是导致错误的行,(JudgeActivity。这不是封闭的类)

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

1 个答案:

答案 0 :(得分:1)

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

因此正确的替换方法是:

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

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