购物车简单实现

//ShopActivity

public class ShopActivity extends AppCompatActivity implements IView ,View.OnClickListener{
    private ShopAdapter adapter;
    private RecyclerView recyclerView_shop;
    IPersentermpl iPersentermpl;
    private TextView text_suan;
    private TextView button;
    String path="http://www.zhaoapi.cn/product/getCarts";
    private CheckBox choose_quan;
    List<Shop.DataBean> list=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop);
        init();
    }
    private void init(){
        iPersentermpl = new IPersentermpl(this);
        recyclerView_shop = findViewById(R.id.shop_jia);
        choose_quan = findViewById(R.id.choose_quan);
        text_suan = findViewById(R.id.text_suan);
        button = findViewById(R.id.button_jie);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        adapter=new ShopAdapter(this);
        recyclerView_shop.setLayoutManager(linearLayoutManager);
        recyclerView_shop.setAdapter(adapter);
        Map<String,String> map=new HashMap<>();
        map.put(Constants.MAP_KEY_GET_PRODUCT_UID,71+"");
        iPersentermpl.setrequest(path,map,Shop.class);
        adapter.setListener(new ShopAdapter.ShopCallBackListener() {
            @Override
            public void callBack(List<Shop.DataBean> list) {
                double totalprice=0;
                int num=0;
                for (int a = 0; a < list.size(); a++) {
                    //获取商家里商品
                    List<Shop.DataBean.ListBean> listAll = list.get(a).getList();
                    for (int i = 0; i < listAll.size(); i++) {
                        num = num + listAll.get(i).getNum();
                        //取选中的状态
                        if (listAll.get(i).isCheck()) {
                            totalprice = totalprice + (listAll.get(i).getPrice() * listAll.get(i).getNum());
                            num = num + listAll.get(i).getNum();
                        }
                    }
                }

                if (num < num) {
                    //不是全部选中
                    choose_quan.setChecked(false);
                } else {
                    //是全部选中
                    choose_quan.setChecked(true);
                }

                text_suan.setText("合计:" + totalprice);
                button.setText("去结算(" + num + ")");
            }
        });
    }
    @Override
    public void swtonSuccess(Object o) {
         Shop bean= (Shop) o;
         List<Shop.DataBean> data = bean.getData();
         adapter.setList(data);
    }
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.choose_quan:
                checkSeller(choose_quan.isChecked());
                adapter.notifyDataSetChanged();
        }
    }
    public void checkSeller(boolean bool){
        double totalPrice=0;
        int num=0;
        //循环遍历商家
        for(int a=0;a<list.size();a++){
            Shop.DataBean dataBean = list.get(a);
            dataBean.setCheck(bool);
            List<Shop.DataBean.ListBean> listAll = this.list.get(a).getList();

        //循环商品
        for (int i=0;i<list.size();i++){
            listAll.get(i).setCheck(bool);
            num+=listAll.get(i).getNum()+num;
            totalPrice+=listAll.get(i).getPrice()+totalPrice;
        }
     }
     if(bool){
         text_suan.setText("合计:"+totalPrice);
         button.setText("去结算:"+num);
     }else {
         text_suan.setText("合计:0.00");
         button.setText("去结算:(0)");
     }
    }
}

//ShopAdapter

public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.ViewHolder> {
    private Context context;
    private List<Shop.DataBean> list;

    public ShopAdapter(Context context) {
        this.context = context;
        list=new ArrayList<>();
    }

    public void setList(List<Shop.DataBean> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ShopAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LinearLayout.inflate(context, R.layout.shangjia, null);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }
    @Override
    public void onBindViewHolder(@NonNull final ShopAdapter.ViewHolder viewHolder, final int i) {
      viewHolder.textView.setText(list.get(i).getSellerName());
        final ProductsAdapter productsAdapter = new ProductsAdapter(context,list.get(i).getList());
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        viewHolder.recyclerView_pin.setLayoutManager(linearLayoutManager);
        viewHolder.recyclerView_pin.setAdapter(productsAdapter);
        viewHolder.check_jia.setChecked(list.get(i).isCheck());
        productsAdapter.setListener(new ProductsAdapter.ShopCallBackListener() {
            @Override
            public void callBack() {
                if(mShopCallBackListener!=null){
                    mShopCallBackListener.callBack(list);
                }
                List<Shop.DataBean.ListBean> listBeans=list.get(i).getList();
                boolean isAllChecked=true;
                for(Shop.DataBean.ListBean bean:listBeans){
                    if(!bean.isCheck()){
                        isAllChecked=false;
                        break;
                    }
                }
                viewHolder.check_jia.setChecked(isAllChecked);
                list.get(i).setCheck(isAllChecked);
            }
        });
        viewHolder.check_jia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.get(i).setCheck(viewHolder.check_jia.isChecked());
                productsAdapter.selectRemoveAll(viewHolder.check_jia.isChecked());
            }
        });
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        RecyclerView recyclerView_pin;
        TextView textView;
        CheckBox check_jia;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            recyclerView_pin = itemView.findViewById(R.id.recy_pin);
            textView = itemView.findViewById(R.id.text_jia);
            check_jia = itemView.findViewById(R.id.checkbox_jia);
        }
    }
    private ShopCallBackListener mShopCallBackListener;

    public void setListener(ShopCallBackListener listener) {
        this.mShopCallBackListener = listener;
    }

    public interface ShopCallBackListener {
        void callBack(List<Shop.DataBean> list);
    }
}

//ProductsAdapter

public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.ViewHolder> {
    private Context context;
    private List<Shop.DataBean.ListBean> list;


    public ProductsAdapter(Context context, List<Shop.DataBean.ListBean> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public ProductsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.shangpin, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ProductsAdapter.ViewHolder viewHolder, final int i) {
        String url = list.get(i).getImages().split("\\|")[0].replace("https", "http");
        Glide.with(context).load(url).into(viewHolder.image_pin);
        viewHolder.text_title.setText(list.get(i).getTitle());
        viewHolder.text_price.setText(list.get(i).getPrice()+"");
        //根据我记录的状态,改变勾选
        viewHolder.checkBox_pin.setChecked(list.get(i).isCheck());
        //商品的跟商家的有所不同,商品添加了选中改变的监听
        viewHolder.checkBox_pin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //优先改变自己的状态
                list.get(i).setCheck(isChecked);
                //回调,目的是告诉activity,有人选中状态被改变
                if(mShopCallBackListener!=null){
                    mShopCallBackListener.callBack();
                }
            }
        });
        viewHolder.customCounterView.setData(this,list,i);
        viewHolder.customCounterView.setOnClick(new CustomCounterView.OnClick() {
            @Override
            public void OnClick() {
                  if(mShopCallBackListener!=null){
                      mShopCallBackListener.callBack();
                  }
            }
        });
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        CheckBox checkBox_pin;
        TextView text_title,text_price;
        ImageView image_pin;
        CustomCounterView customCounterView;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            checkBox_pin = itemView.findViewById(R.id.checkbox_pin);
            text_title = itemView.findViewById(R.id.text_title);
            text_price = itemView.findViewById(R.id.text_price);
            image_pin = itemView.findViewById(R.id.image_pin);
            customCounterView = itemView.findViewById(R.id.custom);
        }
    }
    //修改商品的全选和反选
    public void selectRemoveAll(boolean isSelectAll){
        for (Shop.DataBean.ListBean listBean:list){
            listBean.setCheck(isSelectAll);
        }
    }
    private ShopCallBackListener mShopCallBackListener;
    public interface ShopCallBackListener{
        void callBack();
    }
    public void setListener(ShopCallBackListener shopCallBackListener){
        mShopCallBackListener=shopCallBackListener;
    }
}

//自定义view加减器

public class CustomCounterView extends RelativeLayout implements View.OnClickListener{
    private Context context;
    ImageView image_jian,image_jia;
    EditText edit_num;
    private int nun;
    private int position;
    ProductsAdapter productsAdapter;
    private List<Shop.DataBean.ListBean> list=new ArrayList<>();
    public CustomCounterView(@NonNull Context context) {
        super(context);
        init(context);
    }

    public CustomCounterView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CustomCounterView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    @Override
    public void onDraw(Canvas c) {
        super.onDraw(c);
    }

    public void init(Context context){
        this.context=context;
        View view = View.inflate(context, R.layout.item1, null);
        image_jian = view.findViewById(R.id.image_jian);
        image_jia = view.findViewById(R.id.image_jia);
        edit_num = view.findViewById(R.id.edit_num);
        image_jia.setOnClickListener(this);
        image_jian.setOnClickListener(this);
        addView(view);
        edit_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    String s1 = edit_num.getText().toString();
                    nun=Integer.parseInt(String.valueOf(s1));
                    list.get(position).setNum(nun);
                }catch (Exception e){
                    list.get(position).setNum(1);
                }
                if(monClick!=null){
                    monClick.OnClick();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
    public void setData(ProductsAdapter productsAdapter, List<Shop.DataBean.ListBean> list, int i) {
        this.list=list;
        this.productsAdapter=productsAdapter;
        position=i;
        nun=list.get(i).getNum();
        edit_num.setText(nun+"");
    }
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.image_jia:
                nun++;
                edit_num.setText(nun+"");
                list.get(position).setNum(nun);
                monClick.OnClick();
                productsAdapter.notifyItemChanged(position);
                break;
            case R.id.image_jian:
                if(nun>1){
                    nun--;
                }else
                {
                    Toast.makeText(context,"我是有底线的",Toast.LENGTH_SHORT).show();
                }
                edit_num.setText(nun+"");
                list.get(position).setNum(nun);
                monClick.OnClick();
                productsAdapter.notifyDataSetChanged();
                break;
                default:
                    break;
        }
    }

    //定义接口
    public interface OnClick{
        void OnClick();
    }
    private OnClick monClick;
    public void setOnClick(OnClick onClick){
        monClick=onClick;
    }
}

//编码

  public class Constants {
        public static final String MAP_KEY_GET_PRODUCT_UID= "uid";
    }
//Xml页面
activityshop页面
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".ShopActivity">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
       android:layout_height="0dp"
        android:layout_weight="1">
        <ImageView
            android:id="@+id/image_fan"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="15dp"
            android:background="@drawable/fan"
            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="购物车"
            android:gravity="center"
            android:textColor="#f00"
            android:textSize="25sp"
            />
    </LinearLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/shop_jia"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="8"
        >
    </android.support.v7.widget.RecyclerView>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        >
        <CheckBox
            android:id="@+id/choose_quan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/choose_text"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="全选/全不选"
            android:gravity="center"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="结算:"
            android:gravity="center"
            android:layout_marginLeft="50dp"
            />
        <TextView
            android:id="@+id/text_suan"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="0.00"
            android:gravity="center"
            android:layout_marginLeft="5dp"
            />
        <TextView
            android:id="@+id/button_jie"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="去结算"
            android:background="@color/colorPrimary"
            android:layout_marginLeft="50dp"
            />
    </LinearLayout>
</LinearLayout>
//加减器的页面
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:orientation="horizontal"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/image_jian"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/jian"
        />
    <EditText
        android:id="@+id/edit_num"
        android:layout_width="50dp"
        android:layout_height="30dp"
        android:background="@drawable/shape"
        android:text="1"
        android:gravity="center"
        android:inputType="number"
        />
    <ImageView
        android:id="@+id/image_jia"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/add"
        />
</LinearLayout>

//商家页面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <CheckBox
        android:id="@+id/checkbox_jia"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text_jia"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    </LinearLayout>
     <android.support.v7.widget.RecyclerView
         android:id="@+id/recy_pin"
         android:layout_width="match_parent"
         android:layout_height="match_parent">
     </android.support.v7.widget.RecyclerView>
</LinearLayout>
//商品页面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="match_parent">
    <CheckBox
        android:id="@+id/checkbox_pin"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/image_pin"
        android:layout_width="0dp"
        android:layout_height="100dp"
        android:layout_weight="2"
        />
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="7"
        >
    <TextView
        android:id="@+id/text_title"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        >
    <TextView
        android:id="@+id/text_price"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />
        <ningjiaxin1.bwie.com.drylx.CustomCounterView
            android:id="@+id/custom"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">
        </ningjiaxin1.bwie.com.drylx.CustomCounterView>
    </LinearLayout>
    </LinearLayout>
</LinearLayout>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java购物车简单实现可以通过以下步骤来完成: 1. 创建商品类(Product):定义商品的属性,如商品名称、价格等,并提供相应的构造方法和获取属性值的方法。 2. 创建购物车类(ShoppingCart):购物车类用于管理用户选择的商品。可以使用一个列表或者数组来存储用户选择的商品。购物车类应该提供以下功能: - 添加商品到购物车 - 从购物车中移除商品 - 获取购物车中的所有商品 - 计算购物车中商品的总价 3. 创建主程序类(Main):在主程序类中,可以创建商品对象和购物车对象,并通过调用购物车类的方法来实现购物车的功能。 下面是一个简单的Java购物车实现的示例代码: ```java // 商品类 class Product { private String name; private double price; public Product(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public double getPrice() { return price; } } // 购物车类 class ShoppingCart { private List<Product> products; public ShoppingCart() { products = new ArrayList<>(); } public void addProduct(Product product) { products.add(product); } public void removeProduct(Product product) { products.remove(product); } public List<Product> getProducts() { return products; } public double getTotalPrice() { double totalPrice = 0; for (Product product : products) { totalPrice += product.getPrice(); } return totalPrice; } } // 主程序类 public class Main { public static void main(String[] args) { // 创建商品对象 Product product1 = new Product("商品1", 10.0); Product product2 = new Product("商品2", 20.0); // 创建购物车对象 ShoppingCart shoppingCart = new ShoppingCart(); // 添加商品到购物车 shoppingCart.addProduct(product1); shoppingCart.addProduct(product2); // 获取购物车中的所有商品 List<Product> products = shoppingCart.getProducts(); for (Product product : products) { System.out.println("商品名称:" + product.getName() + ",价格:" + product.getPrice()); } // 计算购物车中商品的总价 double totalPrice = shoppingCart.getTotalPrice(); System.out.println("购物车中商品的总价:" + totalPrice); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值