要解决Android Studio中购物车应用程序中的总计问题,您可以按照以下步骤进行:
CartAdapter
的自定义适配器类,继承自RecyclerView.Adapter
,用于显示购物车中的商品列表。public class CartAdapter extends RecyclerView.Adapter {
private List productList;
public CartAdapter(List productList) {
this.productList = productList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Product product = productList.get(position);
holder.nameTextView.setText(product.getName());
holder.priceTextView.setText(String.valueOf(product.getPrice()));
}
@Override
public int getItemCount() {
return productList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView priceTextView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.nameTextView);
priceTextView = itemView.findViewById(R.id.priceTextView);
}
}
}
RecyclerView
和CartAdapter
显示购物车中的商品列表。public class CartActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private CartAdapter cartAdapter;
private List productList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
// 初始化商品列表数据
productList = new ArrayList<>();
productList.add(new Product("商品1", 10));
productList.add(new Product("商品2", 20));
productList.add(new Product("商品3", 30));
// 初始化RecyclerView和适配器
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
cartAdapter = new CartAdapter(productList);
recyclerView.setAdapter(cartAdapter);
// 计算总计金额
int total = 0;
for (Product product : productList) {
total += product.getPrice();
}
// 显示总计金额
TextView totalTextView = findViewById(R.id.totalTextView);
totalTextView.setText(String.valueOf(total));
}
}
activity_cart.xml
)中,包含一个RecyclerView
来显示商品列表,以及一个TextView
来显示总计金额。
通过以上步骤,您可以在购物车应用程序中显示商品列表,并计算并显示总计金额。