如何从recyclerView删除一项?

时间:2018-07-14 12:52:35

标签: android database android-recyclerview

我的应用程序中有一个数据库,并在recyclerView中显示它。

在recyclerView的每个项目中,我都有一个用于删除项目的ImageView。

我想单击imageView并从数据库和recyclerView中删除项目。

这是mayAdapter:

public class ShoppingCartAdapter extends RecyclerView.Adapter<ShoppingCartAdapter.ShoppingCartViewHolder>{


private final Context context;
private final List<DataModelListShoppingCart> shoppingCartList;
private ShopDatabaseOpenHelper openHelper;

public ShoppingCartAdapter(Context context, List<DataModelListShoppingCart> shoppingCartList, ShopDatabaseOpenHelper openHelper){


    this.context = context;
    this.shoppingCartList = shoppingCartList;
    this.openHelper = openHelper;
}

@NonNull
@Override
public ShoppingCartAdapter.ShoppingCartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.model_shopping_cart_layout,parent,false);
    return new ShoppingCartAdapter.ShoppingCartViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ShoppingCartAdapter.ShoppingCartViewHolder holder, final int position) {
    final DataModelListShoppingCart shoppingCart = shoppingCartList.get(position);


    holder.delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openHelper.deleteProduct(shoppingCart.getId());
            notifyItemRemoved(position);
        }
    });

}

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


 public class ShoppingCartViewHolder extends RecyclerView.ViewHolder{

    private ImageView delete;

    public ShoppingCartViewHolder(View itemView) {
        super(itemView);

        delete = itemView.findViewById(R.id.image_view_clear_shopping_cart);
    }

    }
}

我为ImageView设置了OnClickListener并从数据库中删除了该项目,但该项目仍在这里。当我回到“活动”项目时删除。

如何在单击图像视图后立即删除项目?

2 个答案:

答案 0 :(得分:1)

只需从列表中删除该项目即可。

holder.delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openHelper.deleteProduct(shoppingCart.getId());
            shoppingCartList.remove(position);
            notifyItemRemoved(position);
        }
    });

答案 1 :(得分:1)

您还必须从数据源中删除项目(此处为C:\\Users\\UserName\\AppData\\)。 如果您从db中获得绑定绑定器(onBindViewHolder)中的每个项目,则您的方法将是正确的。