我尝试从我的应用购物车中实施项目删除(我已经使用了本教程http://www.androiddom.com/2012/06/android-shopping-cart-tutorial-part-3.html)。
将商品添加到购物车时,我正在做的是将商品详细信息发送到购物车cartActivity
,然后我在每个商品前面的购物车中编辑按钮。按下它后,它进入编辑屏幕,相应地加载所有数据。在editactivity
我有删除按钮。我应该使用什么作为参考代码?如果是,我该如何获得该代码?
添加的每个项目都有一个产品编号,如下面的屏幕截图所示。
我使用了ShoppingCartHelper.java
public class ShoppingCartHelper {
private static Map<Product, ShoppingCartEntry> cartMap = new HashMap<Product, ShoppingCartEntry>();
public static void setQuantity(Product product, int quantity) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
// If the quantity is zero or less, remove the products
if (quantity <= 0) {
if (curEntry != null)
removeProduct(product);
return;
}
// If a current cart entry doesn't exist, create one
if (curEntry == null) {
curEntry = new ShoppingCartEntry(product, quantity);
cartMap.put(product, curEntry);
return;
}
// Update the quantity
curEntry.setQuantity(quantity);
}
public static int getProductQuantity(Product product) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
if (curEntry != null)
return curEntry.getQuantity();
return 0;
}
public static void removeProduct(Product product) {
cartMap.remove(product);
}
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for (Product p : cartMap.keySet()) {
cartList.add(p);
}
return cartList;
}
}
在editactivity.java
deleteCartButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ShoppingCartHelper.removeProduct(product); //how can I get the product here, it says to define it
}
});
答案 0 :(得分:0)
如果您将项目id
从CartActivity
传递到EditActivity
时遇到问题,可以使用Intent
个额外内容:
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra("id", product.id); // id must be long
startActivity(intent);
EditActivity.java
:
Override
protected void onCreate(Bundle savedInstanceState) {
...
long id = getIntent().getLongExtra("id", 0);
...
}
如果您无法获取ShoppingCartEntry
个实例,但是您拥有Product
个实例,则可以将以下方法添加到ShoppingCartHelper.java
:
public ShoppingCartEntry getByProduct(Product product) {
return cartMap.get(product);
}