android studio实现购物车的代码
时间: 2023-10-21 09:17:07 浏览: 98
您好,以下是针对 Android Studio 实现购物车的代码示例:
1. 在 build.gradle 中添加以下依赖:
```
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
```
2. 创建一个 RecyclerView 来显示购物车列表:
```
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_shopping_cart"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
3. 创建一个适配器类,用于将商品数据显示在 RecyclerView 中:
```
public class ShoppingCartAdapter extends RecyclerView.Adapter<ShoppingCartAdapter.ViewHolder> {
private List<Product> products;
private Context context;
public ShoppingCartAdapter(Context context, List<Product> products) {
this.context = context;
this.products = products;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_product, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Product product = products.get(position);
holder.tvProductName.setText(product.getName());
holder.tvProductPrice.setText("$" + product.getPrice());
holder.btnAddToCart.setVisibility(View.GONE);
}
@Override
public int getItemCount() {
return products.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView tvProductName, tvProductPrice;
Button btnAddToCart;
public ViewHolder(View itemView) {
super(itemView);
tvProductName = itemView.findViewById(R.id.tv_product_name);
tvProductPrice = itemView.findViewById(R.id.tv_product_price);
btnAddToCart = itemView.findViewById(R.id.btn_add_to_cart);
}
}
}
```
4. 在 activity 中创建一个列表,并初始化适配器:
```
List<Product> products = new ArrayList<>();
products.add(new Product("Apple", 1.99));
products.add(new Product("Banana", 0.99));
products.add(new Product("Orange", 0.49));
RecyclerView rvShoppingCart = findViewById(R.id.rv_shopping_cart);
rvShoppingCart.setLayoutManager(new LinearLayoutManager(this));
ShoppingCartAdapter adapter = new ShoppingCartAdapter(this, products);
rvShoppingCart.setAdapter(adapter);
```
这样就完成了一个简单的购物车实现,希望能对您有所帮助。
阅读全文