Android studio实现简单购物车加减商品结算
时间: 2023-12-19 18:07:17 浏览: 151
Android Studio实现简单购物车功能
实现简单购物车加减商品结算,可以按照以下步骤进行:
1. 创建一个商品类,包含商品名称、商品价格、商品数量等属性。
```
public class Goods {
private String name;
private double price;
private int quantity;
public Goods(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
// getter和setter方法
}
```
2. 在Activity中创建一个列表,用于展示购物车中的商品。
```
List<Goods> goodsList = new ArrayList<>();
```
3. 创建一个适配器,将商品列表展示到RecyclerView中。
```
public class GoodsAdapter extends RecyclerView.Adapter<GoodsAdapter.ViewHolder> {
private List<Goods> mGoodsList;
static class ViewHolder extends RecyclerView.ViewHolder {
TextView goodsName;
TextView goodsPrice;
TextView goodsQuantity;
public ViewHolder(View view) {
super(view);
goodsName = view.findViewById(R.id.goods_name);
goodsPrice = view.findViewById(R.id.goods_price);
goodsQuantity = view.findViewById(R.id.goods_quantity);
}
}
public GoodsAdapter(List<Goods> goodsList) {
mGoodsList = goodsList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.goods_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Goods goods = mGoodsList.get(position);
holder.goodsName.setText(goods.getName());
holder.goodsPrice.setText(String.valueOf(goods.getPrice()));
holder.goodsQuantity.setText(String.valueOf(goods.getQuantity()));
}
@Override
public int getItemCount() {
return mGoodsList.size();
}
}
```
4. 在布局文件中添加RecyclerView和结算按钮。
```
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/goods_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp" />
<Button
android:id="@+id/checkout_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="结算" />
```
5. 在Activity中初始化RecyclerView和适配器。
```
RecyclerView recyclerView = findViewById(R.id.goods_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
GoodsAdapter adapter = new GoodsAdapter(goodsList);
recyclerView.setAdapter(adapter);
```
6. 添加添加商品和删除商品的功能。
```
// 添加商品
goodsList.add(new Goods("商品1", 10.0, 1));
adapter.notifyDataSetChanged();
// 删除商品
goodsList.remove(position);
adapter.notifyItemRemoved(position);
```
7. 添加加减商品数量的功能。
```
// 商品数量加1
goods.setQuantity(goods.getQuantity() + 1);
adapter.notifyItemChanged(position);
// 商品数量减1
if (goods.getQuantity() > 0) {
goods.setQuantity(goods.getQuantity() - 1);
adapter.notifyItemChanged(position);
}
```
8. 添加结算功能。
```
double totalPrice = 0;
for (Goods goods : goodsList) {
totalPrice += goods.getPrice() * goods.getQuantity();
}
Toast.makeText(this, "总价为:" + totalPrice, Toast.LENGTH_SHORT).show();
```
这样,一个简单的购物车加减商品结算就实现了。
阅读全文