androidandroid-recyclerviewandroid-adapter

remove selected item from recyclerView on click delete image icon


I want remove selected item from recyclerView list. In my list I have delete image icon each row and I want delete item when clicked delete image icon. How can do it? My adapter code this is see my code how can do it: thank you

 public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ItemViewHolder>{

private Context context;
private List<Items> items=new ArrayList<>();

public ListAdapter(Context context){
    this.context=context;
}
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater=LayoutInflater.from(context);

        View view=layoutInflater.inflate(R.layout.item,parent,false);

    return new ItemViewHolder(view);
}

@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
    holder.bindItem(items.get(position));
}

@Override
public int getItemCount() {

    return items.size();
}

public class ItemViewHolder extends RecyclerView.ViewHolder{
    private TextView titleTextView;
    private ImageView editIcon;
    private ImageView deleteIcon;

    public ItemViewHolder(View itemView) {
        super(itemView);
        titleTextView =itemView.findViewById(R.id.item_title);
        editIcon=itemView.findViewById(R.id.item_edit);
        deleteIcon=itemView.findViewById(R.id.item_delete);
    }

    public void bindItem(Items item){
        titleTextView.setText(item.getTitle());
    }

    public void removeItem(int position){
        items.remove(position);
        notifyItemRemoved(position);
    }
}

public void addItem(Items item){
    items.add(item);
    notifyItemInserted(items.size()-1);
}


}

Solution

  • Try below code

    public ItemViewHolder(View itemView) {
            super(itemView);
            titleTextView =itemView.findViewById(R.id.item_title);
            editIcon=itemView.findViewById(R.id.item_edit);
            deleteIcon=itemView.findViewById(R.id.item_delete);
            // put this code
            deleteIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    removeItem(getAdapterPosition())
                }
            });
        }