购物车模块详细代码

xiaoxiao2025-06-02  43

//先是布局主页面

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent">

    <!--标题栏-->     <RelativeLayout         android:id="@+id/rl_title"         android:layout_width="match_parent"         android:layout_height="48dp">

        <TextView             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_centerInParent="true"             android:text="购物车" />

        <TextView             android:id="@+id/txt_edit_or_finish"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_alignParentRight="true"             android:layout_centerVertical="true"             android:padding="5dp"             android:text="编辑" />

    </RelativeLayout>

    <!--底部结算-->     <RelativeLayout         android:id="@+id/rl_bottom"         android:layout_width="match_parent"         android:layout_height="48dp"         android:layout_alignParentBottom="true">

        <CheckBox             android:id="@+id/cb_total_select"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_centerVertical="true"             android:text="全选" />

        <TextView             android:id="@+id/txt_total_price"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_centerVertical="true"             android:layout_marginLeft="10dp"             android:layout_toRightOf="@id/cb_total_select"             android:textColor="#c23636" />

        <Button             android:id="@+id/btn_calu"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:layout_alignParentRight="true"             android:layout_centerVertical="true"             android:text="结算" />     </RelativeLayout>

    <android.support.v7.widget.RecyclerView         android:id="@+id/rv_shopper"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:layout_above="@id/rl_bottom"         android:layout_below="@id/rl_title"></android.support.v7.widget.RecyclerView>

</RelativeLayout>

//商品布局

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:orientation="vertical">

    <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_gravity="center_vertical"         android:orientation="horizontal"         android:padding="5dp">

        <CheckBox             android:id="@+id/cb_shopper"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:text="@null" />

        <TextView             android:id="@+id/txt_shopper_name"             android:layout_width="match_parent"             android:layout_height="wrap_content" />     </LinearLayout>

    <android.support.v7.widget.RecyclerView         android:id="@+id/rv_product"         android:layout_width="match_parent"         android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

//详情布局

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:orientation="horizontal"     android:paddingBottom="5dp"     android:paddingLeft="20dp"     android:paddingRight="5dp"     android:paddingTop="5dp">

    <CheckBox         android:id="@+id/cb_product"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="@null" />

    <ImageView         android:id="@+id/img_product"         android:layout_width="45dp"         android:layout_height="45dp"         android:layout_marginLeft="10dp"         android:layout_toRightOf="@id/cb_product" />

    <com.bwie.cart1023.widget.AddDecreaseView         android:id="@+id/adv_product"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentRight="true"></com.bwie.cart1023.widget.AddDecreaseView>

    <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_toLeftOf="@id/adv_product"         android:layout_toRightOf="@id/img_product"         android:orientation="vertical">

        <TextView             android:id="@+id/txt_product_name"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:layout_marginLeft="10dp" />

        <TextView             android:id="@+id/txt_single_price"             android:layout_width="match_parent"             android:layout_height="wrap_content" />     </LinearLayout>

</RelativeLayout>

//加减器的布局

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="70dp"     android:layout_height="wrap_content">

    <TextView         android:id="@+id/txt_decrease"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:background="#e78b8b"         android:padding="5dp"         android:text=" - " />

    <TextView         android:id="@+id/txt_add"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentRight="true"         android:background="#e78b8b"         android:padding="5dp"         android:text=" + " />

    <TextView         android:id="@+id/txt_num"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_centerVertical="true"         android:layout_toLeftOf="@id/txt_add"         android:layout_toRightOf="@id/txt_decrease"         android:gravity="center"         android:maxLength="3" /> </RelativeLayout>

//Inter层

package com.bwie.cart1023.inter;

/**  * Created by eric on 2018/10/22.  */

public interface INetCallBack {     void success(Object obj);

    void failed(Exception e); }

//Utils层

package com.bwie.cart1023.utils;

import android.os.Handler; import android.os.Looper;

import com.bwie.cart1023.inter.INetCallBack; import com.google.gson.Gson;

import java.io.IOException; import java.lang.reflect.Type; import java.util.concurrent.TimeUnit;

import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor;

/**  * Created by eric on 2018/10/22.  */

public class HttpUtils {     private static volatile HttpUtils instance;

    private OkHttpClient client;

    private Handler handler = new Handler(Looper.getMainLooper());

    private HttpUtils() {         HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();         interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        client = new OkHttpClient.Builder()                 .connectTimeout(5, TimeUnit.SECONDS)                 .addInterceptor(interceptor)                 .build();     }

    public static HttpUtils getInstance() {         if (instance == null) {             synchronized (HttpUtils.class) {                 if (null == instance) {                     instance = new HttpUtils();                 }             }         }         return instance;     }

    public void get(String url, final INetCallBack callBack, final Type type) {         Request request = new Request.Builder()                 .get()                 .url(url)                 .build();

        Call call = client.newCall(request);         call.enqueue(new Callback() {             @Override             public void onFailure(Call call, final IOException e) {                 handler.post(new Runnable() {                     @Override                     public void run() {                         callBack.failed(e);                     }                 });             }

            @Override             public void onResponse(Call call, Response response) throws IOException {                 String result = response.body().string();                 Gson gson = new Gson();                 final Object o = gson.fromJson(result, type);                 handler.post(new Runnable() {                     @Override                     public void run() {                         callBack.success(o);                     }                 });             }         });     } }

//Utils转换层

package com.bwie.cart1023.utils;

/**  * Created by eric on 2018/10/22.  */

public class StringUtils {     public static String https2Http(String url) {         return url.replace("https", "http");     } }

//bean层

package com.bwie.cart1023.bean;

import java.util.List;

/**  * Created by eric on 2018/10/23.  */

public class MessageBean<T> {     private String msg;     private String code;     private T data;

    public String getMsg() {         return msg;     }

    public void setMsg(String msg) {         this.msg = msg;     }

    public String getCode() {         return code;     }

    public void setCode(String code) {         this.code = code;     }

    public T getData() {         return data;     }

    public void setData(T data) {         this.data = data;     } }

//网络请求层省略

//第三层

package com.bwie.cart1023.bean;

/**  * Created by eric on 2018/10/23.  */

public class Shopper<T> {     private String sellerid;     private String sellerName;     private boolean isChecked;     private T list;

    public String getSellerid() {         return sellerid;     }

    public void setSellerid(String sellerid) {         this.sellerid = sellerid;     }

    public String getSellerName() {         return sellerName;     }

    public void setSellerName(String sellerName) {         this.sellerName = sellerName;     }

    public boolean isChecked() {         return isChecked;     }

    public void setChecked(boolean checked) {         isChecked = checked;     }

    public T getList() {         return list;     }

    public void setList(T list) {         this.list = list;     } }

//M层

package com.bwie.cart1023.cart.model;

import com.bwie.cart1023.inter.INetCallBack; import com.bwie.cart1023.utils.HttpUtils;

import java.lang.reflect.Type;

/**  * Created by eric on 2018/10/23.  */

public class CartModel {     public void getData(String url, INetCallBack callBack, Type type) {         HttpUtils.getInstance().get(url, callBack, type);     } }

//V层

package com.bwie.cart1023.cart.view;

import com.bwie.cart1023.bean.MessageBean; import com.bwie.cart1023.bean.Product; import com.bwie.cart1023.bean.Shopper;

import java.util.List;

/**  * Created by eric on 2018/10/23.  */

public interface IView {     void success(MessageBean<List<Shopper<List<Product>>>> data);

    void failed(Exception e); }

 

//P层

package com.bwie.cart1023.cart.presenter;

import com.bwie.cart1023.bean.MessageBean; import com.bwie.cart1023.bean.Product; import com.bwie.cart1023.bean.Shopper; import com.bwie.cart1023.cart.model.CartModel; import com.bwie.cart1023.cart.view.IView; import com.bwie.cart1023.inter.INetCallBack; import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type; import java.util.List;

/**  * Created by eric on 2018/10/23.  */

public class CartPresenter {     private IView iv;     private CartModel model;

    public void attach(IView iv) {         this.iv = iv;         model = new CartModel();     }

    public void getData() {         String url = "http://www.zhaoapi.cn/product/getCarts?uid=1538";         Type type = new TypeToken<MessageBean<List<Shopper<List<Product>>>>>() {         }.getType();

        model.getData(url, new INetCallBack() {             @Override             public void success(Object obj) {                 MessageBean<List<Shopper<List<Product>>>> data = (MessageBean<List<Shopper<List<Product>>>>) obj;                 iv.success(data);             }

            @Override             public void failed(Exception e) {                 iv.failed(e);             }         }, type);

    }

    public void detach() {         if (iv != null) {             iv = null;         }     } }

//加减器

package com.bwie.cart1023.widget;

import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView;

import com.bwie.cart1023.R;

/**  * Created by eric on 2018/10/23.  */

public class AddDecreaseView extends RelativeLayout implements View.OnClickListener {     private TextView txtAdd;     private TextView txtDecrease;     private TextView txtNum;

    private int num;

    public interface OnAddDecreaseClickListener {         void add(int num);

        void decrease(int num);     }

    private OnAddDecreaseClickListener listener;

    public void setOnAddDecreaseClickListener(OnAddDecreaseClickListener listener) {         this.listener = listener;     }

    public AddDecreaseView(Context context) {         this(context, null);     }

    public AddDecreaseView(Context context, AttributeSet attrs) {         this(context, attrs, 0);     }

    public AddDecreaseView(Context context, AttributeSet attrs, int defStyleAttr) {         super(context, attrs, defStyleAttr);         init(context);     }

    private void init(Context context) {         View.inflate(context, R.layout.item_add_decrease, this);         txtAdd = findViewById(R.id.txt_add);         txtDecrease = findViewById(R.id.txt_decrease);         txtNum = findViewById(R.id.txt_num);

        txtNum.setText("1");

        txtAdd.setOnClickListener(this);         txtDecrease.setOnClickListener(this);

    }

    public void setNum(int num) {         this.num = num;         txtNum.setText(num + "");     }

    public int getNum() {         return num;     }

    @Override     public void onClick(View v) {         switch (v.getId()) {             case R.id.txt_add:                 num++;                 txtNum.setText(num + "");                 if (listener != null) {                     listener.add(num);                 }                 break;             case R.id.txt_decrease:                 if (num > 1) {                     num--;                 }                 txtNum.setText(num + "");                 if (listener != null) {                     listener.decrease(num);                 }                 break;         }     } }

 

//两个Adapter

package com.bwie.cart1023.adapter;

import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView;

import com.bumptech.glide.Glide; import com.bwie.cart1023.R; import com.bwie.cart1023.bean.Product; import com.bwie.cart1023.utils.StringUtils; import com.bwie.cart1023.widget.AddDecreaseView;

import java.util.List;

/**  * Created by eric on 2018/10/23.  */

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {     private Context context;     private List<Product> list;

    // 二级条目(商品)点击监听     public interface OnProductClickListener {         void onProductClick(int position, boolean isChecked);     }

    private OnProductClickListener productClickListener;

    public void setOnProductClickListener(OnProductClickListener listener) {         this.productClickListener = listener;     }

    // 加减器发生变化的监听     public interface OnAddDecreaseProductListener {         void onChange(int position, int num);     }

    private OnAddDecreaseProductListener productListener;

    public void setOnAddDecreaseProductListener(OnAddDecreaseProductListener listener) {         this.productListener = listener;     }

    public ProductAdapter(Context context, List<Product> list) {         this.context = context;         this.list = list;     }

    @NonNull     @Override     public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {         View v = View.inflate(context, R.layout.item_product, null);         ViewHolder holder = new ViewHolder(v);         return holder;     }

    @Override     public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {         final Product product = list.get(position);         String images = product.getImages();         // 商品图片         if (!TextUtils.isEmpty(images)) {             String[] strings = images.split("\\|");             if (strings.length > 0) {                 Glide.with(context)                         .load(StringUtils.https2Http(strings[0]))                         .into(holder.imgProduct);             }         }

        holder.txtProductName.setText(product.getTitle());         holder.txtSinglePriice.setText(String.valueOf(product.getPrice()));

        holder.advProduct.setNum(product.getNum());         // 加减器添加点击事件         holder.advProduct.setOnAddDecreaseClickListener(new AddDecreaseView.OnAddDecreaseClickListener() {             @Override             public void add(int num) {                 product.setNum(num);

                if (productListener != null) {                     productListener.onChange(position, num);                 }             }

            @Override             public void decrease(int num) {                 product.setNum(num);                 if (productListener != null) {                     productListener.onChange(position, num);                 }             }         });

        // 商品的复选框         holder.cbProduct.setOnCheckedChangeListener(null);         holder.cbProduct.setChecked(product.isChecked());         holder.cbProduct.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {             @Override             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {                 product.setChecked(isChecked);                 if (productClickListener != null) {                     productClickListener.onProductClick(position, isChecked);                 }             }         });

    }

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

    class ViewHolder extends RecyclerView.ViewHolder {         private CheckBox cbProduct;         private ImageView imgProduct;         private TextView txtProductName;         private TextView txtSinglePriice;         private AddDecreaseView advProduct;

        public ViewHolder(View itemView) {             super(itemView);             cbProduct = itemView.findViewById(R.id.cb_product);             imgProduct = itemView.findViewById(R.id.img_product);             txtSinglePriice = itemView.findViewById(R.id.txt_single_price);             advProduct = itemView.findViewById(R.id.adv_product);             txtProductName = itemView.findViewById(R.id.txt_product_name);         }     } }

 

//另一个Adapter

package com.bwie.cart1023.adapter;

import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView;

import com.bwie.cart1023.R; import com.bwie.cart1023.bean.Product; import com.bwie.cart1023.bean.Shopper;

import java.util.List;

/**  * Created by eric on 2018/10/23.  */

public class ShopperAdapter extends RecyclerView.Adapter<ShopperAdapter.ViewHolder> {     private Context context;     private List<Shopper<List<Product>>> list;

    public ShopperAdapter(Context context, List<Shopper<List<Product>>> list) {         this.context = context;         this.list = list;     }

    // 一级列表(商家)发生变化的接口     public interface OnShopperClickListener {         void onShopperClick(int position, boolean isCheck);     }

    private OnShopperClickListener shopperClickListener;

    public void setOnShopperClickListener(OnShopperClickListener listener) {         this.shopperClickListener = listener;     }

    // 二级列表的加减器监听     private ProductAdapter.OnAddDecreaseProductListener productListener;

    public void setOnAddDecreaseProductListener(ProductAdapter.OnAddDecreaseProductListener listener) {         this.productListener = listener;     }

    @NonNull     @Override     public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {         View v = View.inflate(context, R.layout.item_shopper, null);         ViewHolder holder = new ViewHolder(v);         return holder;     }

    @Override     public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {         final Shopper<List<Product>> shopper = list.get(position);         holder.txtShopperName.setText(shopper.getSellerName());

        // 产品的列表         RecyclerView.LayoutManager pLayoutManager = new LinearLayoutManager(context);         holder.rvProduct.setLayoutManager(pLayoutManager);         final ProductAdapter adapter = new ProductAdapter(context, shopper.getList());         // 给二级列表添加一个加减器的监听         if (productListener != null) {             adapter.setOnAddDecreaseProductListener(productListener);         }         // 二级条目(商品)复选框点击事件         adapter.setOnProductClickListener(new ProductAdapter.OnProductClickListener() {             @Override             public void onProductClick(int position, boolean isChecked) {                 // 当前商品未选中,商家也就未选中                 if (!isChecked) {                     shopper.setChecked(false);                     // 只要是当前条目未选中,全选复选框也就没选中                     shopperClickListener.onShopperClick(position, false);                 } else {                     // 当前商品如果选中,需要遍历商家所有的商品是否选中                     // 循环遍历之前先设置一个true标志位,只要有一条商品没有被选中,商家也就选中,标志位变成false                     boolean isAllProductSelected = true;                     for (Product product : shopper.getList()) {                         if (!product.isChecked()) {                             isAllProductSelected = false;                             break;                         }                     }                     shopper.setChecked(isAllProductSelected);                     // 当前商品选中时,需要循环遍历所有的商家是否被选中来确认外部全选复选框的状态                     shopperClickListener.onShopperClick(position, true);                 }                 // 数据发生变化之后刷新适配器                 notifyDataSetChanged();                 productListener.onChange(0, 0);             }         });

        holder.rvProduct.setAdapter(adapter);

        // 先取消掉之前的点击变化监听         holder.cbSHopper.setOnCheckedChangeListener(null);

        // 设置好初始化的状态         holder.cbSHopper.setChecked(shopper.isChecked());

        // 等设置完初始化状态之后再设置我们自己的监听         // 商家列表中的复选框         holder.cbSHopper.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {             @Override             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {                 shopper.setChecked(isChecked);

                // 1.商家被选中的时候,子类所有的商品应该被选中 //                if (isChecked) {                 List<Product> productList = shopper.getList();                 for (Product product : productList) {                     product.setChecked(isChecked);                 }                 // 子类商品的适配器刷新                 adapter.notifyDataSetChanged(); //                }                 // 当点击一级条目的时候,外部的全选按钮状态发生变化                 if (shopperClickListener != null) {                     shopperClickListener.onShopperClick(position, isChecked);                 }             }         });     }

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

    class ViewHolder extends RecyclerView.ViewHolder {         private CheckBox cbSHopper;         private TextView txtShopperName;         private RecyclerView rvProduct;

        public ViewHolder(View itemView) {             super(itemView);             cbSHopper = itemView.findViewById(R.id.cb_shopper);             txtShopperName = itemView.findViewById(R.id.txt_shopper_name);             rvProduct = itemView.findViewById(R.id.rv_product);         }     } }

 

 

 

 

 

 

 

转载请注明原文地址: https://www.6miu.com/read-5031166.html

最新回复(0)