购物车

xiaoxiao2025-06-26  10

<?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"?> <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"?> <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="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>

public interface INetCallBack {     void success(Object obj);

    void failed(Exception e); }  

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

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);                     }                 });             }         });     } } 八

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);     } }  

封装bean类

1

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;     } } 2

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;     } } 3

package com.bwie.cart1023.bean;

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

public class Product {

    /**      * bargainPrice : 22.9      * createtime : 2017-10-14T21:48:08      * detailUrl : https://item.m.jd.com/product/2542855.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends      * images : https://m.360buyimg.com/n0/jfs/t1930/284/2865629620/390243/e3ade9c4/56f0a08fNbd3a1235.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2137/336/2802996626/155915/e5e90d7a/56f0a09cN33e01bd0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t1882/31/2772215910/389956/c8dbf370/56f0a0a2Na0c86ea6.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2620/166/2703833710/312660/531aa913/57709035N33857877.jpg!q70.jpg      * num : 1      * pid : 24      * price : 288      * pscid : 2      * selected : 0      * sellerid : 1      * subhead : 三只松鼠零食特惠,专区满99减50,满199减100,火速抢购》      * title : 三只松鼠 坚果炒货 零食奶油味 碧根果225g/袋      */

    private float bargainPrice;     private String createtime;     private String detailUrl;     private String images;     private int num;     private int pid;     private float price;     private int pscid;     private int selected;     private int sellerid;     private String subhead;     private String title;     private boolean isChecked;

    public float getBargainPrice() {         return bargainPrice;     }

    public void setBargainPrice(float bargainPrice) {         this.bargainPrice = bargainPrice;     }

    public String getCreatetime() {         return createtime;     }

    public void setCreatetime(String createtime) {         this.createtime = createtime;     }

    public String getDetailUrl() {         return detailUrl;     }

    public void setDetailUrl(String detailUrl) {         this.detailUrl = detailUrl;     }

    public String getImages() {         return images;     }

    public void setImages(String images) {         this.images = images;     }

    public int getNum() {         return num;     }

    public void setNum(int num) {         this.num = num;     }

    public int getPid() {         return pid;     }

    public void setPid(int pid) {         this.pid = pid;     }

    public float getPrice() {         return price;     }

    public void setPrice(float price) {         this.price = price;     }

    public int getPscid() {         return pscid;     }

    public void setPscid(int pscid) {         this.pscid = pscid;     }

    public int getSelected() {         return selected;     }

    public void setSelected(int selected) {         this.selected = selected;     }

    public int getSellerid() {         return sellerid;     }

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

    public String getSubhead() {         return subhead;     }

    public void setSubhead(String subhead) {         this.subhead = subhead;     }

    public String getTitle() {         return title;     }

    public void setTitle(String title) {         this.title = title;     }

    public boolean isChecked() {         return isChecked;     }

    public void setChecked(boolean checked) {         isChecked = checked;     } } 主要别忘记 复选框的类型  自行定义

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); } 十

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.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);         }     } } 十二

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);         }     } } 十三  加减器

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;         }     } } 十四

package com.bwie.cart1023;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.Toast;

import com.bwie.cart1023.adapter.ProductAdapter; import com.bwie.cart1023.adapter.ShopperAdapter; import com.bwie.cart1023.bean.MessageBean; import com.bwie.cart1023.bean.Product; import com.bwie.cart1023.bean.Shopper; import com.bwie.cart1023.cart.presenter.CartPresenter; import com.bwie.cart1023.cart.view.IView;

import java.util.ArrayList; import java.util.List;

public class MainActivity extends AppCompatActivity implements IView {     private static final String TAG = "MainActivity";     //    MessageBean<List<ShopperAdapter<List<Product>>>>     private TextView txtEditFinish;     private CheckBox cbTotal;     private TextView txtPrice;     private Button btnCalu;     private RecyclerView rvShoper;

    private CartPresenter presenter;     private ShopperAdapter adapter;

    private List<Shopper<List<Product>>> list;

    @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);

        initView();         initData();         setListener();

    }

    private void setListener() {

        cbTotal.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 boolean isChecked = cbTotal.isChecked();                 // 遍历一级列表,和下方的全选状态一致                 for (Shopper<List<Product>> listShopper : list) {                     listShopper.setChecked(isChecked);                     // 遍历二级列表,和下方的全选状态一致                     List<Product> products = listShopper.getList();                     for (Product product : products) {                         product.setChecked(isChecked);                     }                 }                 adapter.notifyDataSetChanged();             }         });     }

    private void initData() {         list = new ArrayList<>();         // 商家的列表         adapter = new ShopperAdapter(this, list);         // 添加一级条目(商家)状态发生变化时         adapter.setOnShopperClickListener(new ShopperAdapter.OnShopperClickListener() {             @Override             public void onShopperClick(int position, boolean isCheck) {                 // 为了效率考虑,当点击状态变成未选中时,全选按钮肯定就不是全选了,就不用再循环一次                 if (!isCheck) {                     cbTotal.setChecked(false);                 } else {                     // 如果是商家变成选中状态时,需要循环遍历所有的商家是否被选中                     // 循环遍历之前先设置一个true标志位,只要有一个是未选中就改变这个标志位为false                     boolean isAllShopperChecked = true;                     for (Shopper<List<Product>> listShopper : list) {                         // 只要有一个商家没有被选中,全选复选框就变成未选中状态,并且结束循环                         if (!listShopper.isChecked()) {                             isAllShopperChecked = false;                             break;                         }                     }                     cbTotal.setChecked(isAllShopperChecked);                 }

                // 一级条目发生变化时,计算一下总价                 calculatePrice();             }         });

        adapter.setOnAddDecreaseProductListener(new ProductAdapter.OnAddDecreaseProductListener() {             @Override             public void onChange(int position, int num) {                 calculatePrice();             }         });

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);         rvShoper.setLayoutManager(layoutManager);         rvShoper.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));         rvShoper.setAdapter(adapter);

        presenter = new CartPresenter();         presenter.attach(this);         presenter.getData();     }

    // 计算商品总价     private void calculatePrice() {         // 遍历商家         float totalPrice = 0;         for (Shopper<List<Product>> listShopper : list) {             // 遍历商家的商品             List<Product> list = listShopper.getList();             for (Product product : list) {                 // 如果商品被选中                 if (product.isChecked()) {                     totalPrice += product.getNum() * product.getPrice();                 }             }         }

        txtPrice.setText("总价:" + totalPrice);

    }

    private void initView() {         txtEditFinish = findViewById(R.id.txt_edit_or_finish);         cbTotal = findViewById(R.id.cb_total_select);         txtPrice = findViewById(R.id.txt_total_price);         btnCalu = findViewById(R.id.btn_calu);         rvShoper = findViewById(R.id.rv_shopper);     }

    @Override     public void success(MessageBean<List<Shopper<List<Product>>>> data) {         if (data != null) {             // 获取商家列表             List<Shopper<List<Product>>> shoppers = data.getData();             if (shoppers != null) {                 list.clear();                 list.addAll(shoppers);                 adapter.notifyDataSetChanged();             }         }     }

    @Override     public void failed(Exception e) {         Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();     }

    @Override     protected void onDestroy() {         super.onDestroy();         if (presenter != null) {             presenter.detach();         }     } }  

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

最新回复(0)