无法从ViewHolder(RecyclerView)中调用适配器中的方法

时间:2017-07-27 11:00:33

标签: java android

我试图在用户点击它时从我的RecyclerView中删除一个项目。但是,即使适配器中的删除方法是公共的,我也会收到错误'无法解析方法delete(int)'当试图打电话'删除'来自MyViewHolder中onClick的方法。

是什么给出的?它是公开的,为什么我不称它为什么呢?

GroceryItemAdapter

public class GroceryItemAdapter extends RecyclerView.Adapter<MyViewHolder> {
    private LayoutInflater inflater;
    private Context context;

    List<MetaData> data = Collections.emptyList();

    public GroceryItemAdapter(Context context, List<MetaData> data) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.data = data;
    }

    public void delete(int position) {
        data.remove(position);
        notifyItemRemoved(position);
    }


    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.grocery_item_row, parent, false);
        MyViewHolder holder = new MyViewHolder(view);
        Log.i("GroceryHero", "onCreateViewHolder called");

        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        MetaData current = data.get(position);
        holder.title.setText(current.title);
        holder.icon.setImageResource(current.iconid);
        Log.i("GroceryHero","onBindViewHolder called " + position);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

}

MyViewHolder:

class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
ImageView icon;

public MyViewHolder(View itemView) {
    super(itemView);
    Log.i("GroceryHero", "MyViewHolder called");
    title = (TextView) itemView.findViewById(R.id.grocery_text);
    icon = (ImageView) itemView.findViewById(R.id.grocery_icon);
    itemView.setOnClickListener(this);
 }

@Override
public void onClick(View v) {
    Toast.makeText(v.getContext(), "Item clicked at " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
    delete(getAdapterPosition()); // ERROR: Cannot resolve method 
}
}

1 个答案:

答案 0 :(得分:3)

您正试图从视图持有者类中调用delete。但delete是适配器类的方法。您可以将适配器实例传递给onCreateViewHolder中的视图持有者,并将其存储为私有字段。

GroceryItemAdapter mAdapter;
public MyViewHolder(View itemView, GroceryItemAdapter adapter) {
    mAdapter = adapter;
    ...
}

// now you can call
mAdapter.delete(getAdapterPosition());