购物车+订单

本文将探讨如何实现一个购物车及其关联的订单系统。主要内容包括购物车的添加、删除和管理商品功能,以及订单的创建、支付和状态管理。在实现过程中,会涉及到权限控制的设置和管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


依赖

权限自己添加

implementation 'com.squareup.okhttp3:okhttp:3.9.1'
implementation 'com.google.code.gson:gson:2.8.+'
compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
compile 'com.youth.banner:banner:1.4.9'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.hjm:BottomTabBar:1.1.1'
compile 'com.github.bumptech.glide:glide:3.6.1'
net

package com.example.lenovo.myapplication.net;

import android.os.Handler;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public class OkHttpUtils {

    private static OkHttpUtils OK_HTTP_UTILS = null;
    //定义一个Handler
    private static Handler handler = new Handler();

    private OkHttpUtils() {
    }
    /**
     * 得到OkHttpUtils实例对象
     *
     * @return
     */
    public static OkHttpUtils getInstance() {

        if (null == OK_HTTP_UTILS) {

            synchronized (OkHttpUtils.class) {

                if (null == OK_HTTP_UTILS) {
                    OK_HTTP_UTILS = new OkHttpUtils();
                }
            }

        }
        return OK_HTTP_UTILS;

    }

    /**
     * Get请求
     *
     * @param path http://www.baidu.com?key=value&key=value
     * @param onFinishListener
     */
    public void doGet(String path, Map<String,String> map, final OnFinishListener onFinishListener) {

        //Http:/www.baidu.com?key=ddd&
        StringBuffer sb = new StringBuffer();
        sb.append(path);
        //判断path是否包含一个
        if(sb.indexOf("?") != -1){
            //判断"?"是否在最后一个
            if(sb.indexOf("?") != sb.length() -1){
                sb.append("&");
            }
        }else{
            sb.append("?");
        }

        //遍历map集合中所有请求参数
        for (Map.Entry<String, String> entry: map.entrySet()){
            sb.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }

        //判断get请求路径最后是否包含一个"&"
        if(sb.lastIndexOf("&") != -1){
            sb.deleteCharAt(sb.length() - 1);
        }


        OkHttpClient okHttpClient = new OkHttpClient();

        //构建请求项
        Request request = new Request.Builder()
                .get()
                .url(sb.toString())
                .build();

        Call call = okHttpClient.newCall(request);
        //execute 子线程  enqueue //
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                //请求失败

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onFinishListener.onFailed(e.getMessage());
                    }
                });


            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //得到服务器的响应结果
                final String result = response.body().string();

                //请求成功
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //主线程当中执行
                        onFinishListener.onSuccess(result);
                    }
                });
            }
        });

    }


    /**
     * post请求
     *
     * @param path
     * @param map
     * @param onFinishListener
     */
    public void doPost(String path, Map<String, String> map, final OnFinishListener onFinishListener) {


        OkHttpClient okHttpClient = new OkHttpClient();

        //构建参数的对象
        FormBody.Builder builder = new FormBody.Builder();

        //遍历map集合,获取用户的key/value
        for (String key : map.keySet()) {
            builder.add(key, map.get(key));
        }

        /*FormBody body = new FormBody.Builder()
                .add("mobile",mobile)
                .add("password",password)
                .build();*/
        //构建请求项
        final Request request = new Request.Builder()
                .post(builder.build())
                .url(path)
                .build();
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onFinishListener.onFailed(e.getMessage());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String result = response.body().string();//这句话必须放到子线程里


                System.out.println("OkHttUitls 线程名 : " + Thread.currentThread().getName());

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onFinishListener.onSuccess(result);
                    }
                });

            }
        });
    }


    /**
     * 上传文件
     * @param path 上传文件路径
     * @param params  上传的参数
     * @param onFinishListener 监听
     */
    public void upLoadFile(String path, Map<String,Object> params, final OnFinishListener onFinishListener){

        OkHttpClient okHttpClient = new OkHttpClient();


        MultipartBody.Builder builder = new MultipartBody.Builder();
        //设设置类型 以表单的形式提交
        builder.setType(MultipartBody.FORM);

        for (Map.Entry<String, Object> entry: params.entrySet()){

            Object object = entry.getValue();
            if(!(object instanceof File)){
                builder.addFormDataPart(entry.getKey(),object.toString());
            }else{
                File file = (File) object;
                builder.addFormDataPart(entry.getKey(),file.getName().trim(),
                        RequestBody.create(MediaType.parse("img/png"),file));

                //img/png -> application/octet-stream
            }
        }

        Request request = new Request.Builder()
                .post(builder.build())
                .url(path)
                .build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onFinishListener.onFailed(e.getMessage());
                    }
                });
            }
            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                //判断服务器是否响应成功
                if(response.isSuccessful()){

                    final String result = response.body().string();

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            onFinishListener.onSuccess(result);
                        }
                    });

                }else{

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            //服务器响应失败
                            onFinishListener.onFailed(response.message());

                        }
                    });
                }
            }
        });
    }
}
package com.example.lenovo.myapplication.net;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public interface OnFinishListener {

    void onFailed(String msg);

    void onSuccess(Object obj);
}
model
package com.example.lenovo.myapplication.model;

import android.os.Handler;
import android.util.Log;

import com.example.lenovo.myapplication.bean.ShopCarBean;
import com.example.lenovo.myapplication.net.OkHttpUtils;
import com.example.lenovo.myapplication.net.OnFinishListener;
import com.example.lenovo.myapplication.presenter.ShopPresenterface;
import com.google.gson.Gson;

import java.util.HashMap;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public class ShopModel {
    private Handler handler = new Handler();
   public void shopcar (String uid, String source,final ShopPresenterface shopPresenterface){

       HashMap<String,String> map = new HashMap<>();
       map.put("uid",uid);
       map.put("source",source);
       OkHttpUtils.getInstance().doGet("http://120.27.23.105/product/getCarts", map, new OnFinishListener() {
           @Override
           public void onFailed(String msg) {

           }
           @Override
           public void onSuccess(final Object obj) {
               handler.post(new Runnable() {
                   @Override
                   public void run() {
                       String s = obj.toString();
                       Gson gson = new Gson();
                       ShopCarBean bean = gson.fromJson(s,ShopCarBean.class);
                       shopPresenterface.onSuccess(bean.getData());
                       Log.e("zzz","123");
                   }
               });
           }
       });

   }
}
package com.example.lenovo.myapplication.model;

import android.os.Handler;

import com.example.lenovo.myapplication.bean.DinDanBean;
import com.example.lenovo.myapplication.net.OkHttpUtils;
import com.example.lenovo.myapplication.net.OnFinishListener;
import com.example.lenovo.myapplication.present.Dindaninterface;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public class Dindanmodel {

    private Handler handler = new Handler();

    public void getdin(String uid, final Dindaninterface dindaninterface)
    {
        HashMap<String,String> map = new HashMap<>();
        map.put("uid",uid);
        OkHttpUtils.getInstance().doGet("https://www.zhaoapi.cn/product/getOrders", map, new OnFinishListener() {
            @Override
            public void onFailed(String msg) {

            }

            @Override
            public void onSuccess(Object obj) {
                final String s = obj.toString();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        DinDanBean bean = gson.fromJson(s, DinDanBean.class);
                        List<DinDanBean.DataBean> data = bean.getData();
                        dindaninterface.onSuccess(data);
                    }
                });

            }
        });
    }
}
bean包
package com.example.lenovo.myapplication.bean;

import java.util.List;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public class DinDanBean {

    /**
     * msg : 请求成功
     * code : 0
     * data : [{"createtime":"2017-10-19T20:28:43","orderid":20,"price":100,"status":2,"title":"订单标题测试3","uid":71},{"createtime":"2017-10-19T20:44:40","orderid":31,"price":11800,"status":2,"title":"订单标题测试14","uid":71},{"createtime":"2017-10-19T20:44:51","orderid":32,"price":11800,"status":2,"title":"订单标题测试15","uid":71},{"createtime":"2017-10-20T08:02:07","orderid":43,"price":11800,"status":2,"title":"订单标题测试","uid":71},{"createtime":"2017-10-20T08:02:16","orderid":44,"price":11800,"status":2,"title":"订单标题测试","uid":71},{"createtime":"2017-10-22T15:14:39","orderid":890,"price":11800,"status":2,"title":"","uid":71},{"createtime":"2017-11-09T09:17:20","orderid":1446,"price":99.99,"status":2,"title":"订单标题测试","uid":71},{"createtime":"2017-11-09T09:20:58","orderid":1447,"price":567,"status":2,"title":"订单标题测试","uid":71},{"createtime":"2017-11-09T09:20:58","orderid":1448,"price":256.99,"status":2,"title":"订单标题测试","uid":71},{"createtime":"2017-11-09T09:20:58","orderid":1449,"price":399,"status":2,"title":"订单标题测试","uid":71}]
     * page : 1
     */

    private String msg;
    private String code;
    private String page;
    private List<DataBean> 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 String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        /**
         * createtime : 2017-10-19T20:28:43
         * orderid : 20
         * price : 100.0
         * status : 2
         * title : 订单标题测试3
         * uid : 71
         */

        private String createtime;
        private String orderid;
        private String price;
        private String status;
        private String title;
        private String uid;

        public String getCreatetime() {
            return createtime;
        }

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

        public String getOrderid() {
            return orderid;
        }

        public void setOrderid(String orderid) {
            this.orderid = orderid;
        }

        public String getPrice() {
            return price;
        }

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

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getTitle() {
            return title;
        }

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

        public String getUid() {
            return uid;
        }

        public void setUid(String uid) {
            this.uid = uid;
        }
    }
}
package com.example.lenovo.myapplication.bean;

import java.util.List;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public class ShopCarBean {

    /**
     * msg : 请求成功
     * code : 0
     * data : [{"list":[{"bargainPrice":11800,"createtime":"2017-10-14T21:38:26","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","num":1,"pid":69,"price":16999,"pscid":40,"selected":0,"sellerid":13,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家13","sellerid":"13"},{"list":[{"bargainPrice":11800,"createtime":"2017-10-14T21:48:08","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","num":2,"pid":77,"price":38999.99,"pscid":40,"selected":0,"sellerid":21,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家21","sellerid":"21"}]
     */

    private String msg;
    private String code;
    private List<DataBean> 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 List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
        /**
         * list : [{"bargainPrice":11800,"createtime":"2017-10-14T21:38:26","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","num":1,"pid":69,"price":16999,"pscid":40,"selected":0,"sellerid":13,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}]
         * sellerName : 商家13
         * sellerid : 13
         */

        private String sellerName;
        private String sellerid;
        private List<ListBean> list;
        private boolean isGroupChoosed;

        public boolean isGroupChoosed() {
            return isGroupChoosed;
        }

        public void setGroupChoosed(boolean groupChoosed) {
            isGroupChoosed = groupChoosed;
        }

        public String getSellerName() {
            return sellerName;
        }

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

        public String getSellerid() {
            return sellerid;
        }

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

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public static class ListBean {
            /**
             * bargainPrice : 11800.0
             * createtime : 2017-10-14T21:38:26
             * detailUrl : https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1
             * images : https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg
             * num : 1
             * pid : 69
             * price : 16999.0
             * pscid : 40
             * selected : 0
             * sellerid : 13
             * subhead : 购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)
             * title : 全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G
             */

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

            public boolean isChildChoosed() {
                return isChildChoosed;
            }

            public void setChildChoosed(boolean childChoosed) {
                isChildChoosed = childChoosed;
            }

            public double getBargainPrice() {
                return bargainPrice;
            }

            public void setBargainPrice(double 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 double getPrice() {
                return price;
            }

            public void setPrice(double 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;
            }
        }
    }


}
adapter
package com.example.lenovo.myapplication.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.lenovo.myapplication.R;
import com.example.lenovo.myapplication.bean.DinDanBean;

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

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public  class Dindanadapter extends RecyclerView.Adapter<Dindanadapter.ViewHolder>{

    private Context context;
    private List<DinDanBean.DataBean>  list = new ArrayList<>();

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

    public Dindanadapter(Context context) {
        this.context = context;
    }

    @Override
    public Dindanadapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(Dindanadapter.ViewHolder holder, int position) {

        holder.createTime.setText(list.get(position).getCreatetime());
        holder.price.setText(list.get(position).getPrice());
        holder.number.setText(list.get(position).getOrderid());
    }

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

    class ViewHolder extends RecyclerView.ViewHolder{

        private  TextView price;
        private  TextView number;
        private  TextView createTime;
        public ViewHolder(View itemView) {
            super(itemView);
           price = itemView.findViewById(R.id.price);
            number = itemView.findViewById(R.id.number);
            createTime = itemView.findViewById(R.id.createTime);
        }
    }
}


package com.example.lenovo.myapplication.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.lenovo.myapplication.R;
import com.example.lenovo.myapplication.bean.ShopCarBean;
import java.util.ArrayList;
import java.util.List;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public class MyExpandAdapter extends BaseExpandableListAdapter{

    private Context context;
    private List<ShopCarBean.DataBean> list = new ArrayList<>();
    private ModifyGoodsItemNumberListener modifyGoodsItemNumberListener;
    private CheckGroupItemListener checkGroupItemListener;
    //接收是否处于编辑状态的一个boolean值
    private boolean isEditor;
    public MyExpandAdapter(Context context) {
        this.context = context;
    }

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

    public void  setCheckGroupItemListener(CheckGroupItemListener checkGroupItemListener){
        this.checkGroupItemListener = checkGroupItemListener;
    }

    public void setModifyGoodsItemNumberListener(ModifyGoodsItemNumberListener modifyGoodsItemNumberListener){
        this.modifyGoodsItemNumberListener = modifyGoodsItemNumberListener;
    }
    public void showDeleteButton(boolean isEditor){
        this.isEditor = isEditor;
        //刷新适配器
        notifyDataSetChanged();
    }
    @Override
    public int getGroupCount() {
        return list.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return list.get(groupPosition).getList().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return list.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return list.get(groupPosition).getList().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

        if (convertView == null)
        {
          convertView = LayoutInflater.from(context).inflate(R.layout.layout_group_item, parent, false);
        }
        final CheckBox ck_group_choosed = convertView.findViewById(R.id.ck_group_choosed);
        if (list.get(groupPosition).isGroupChoosed())
        {
            ck_group_choosed.setChecked(true);
        }
        else
        {
            ck_group_choosed.setChecked(false);
        }
        ck_group_choosed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkGroupItemListener.checkGroupItem(groupPosition,((CheckBox)v).isChecked());
            }
        });
          ck_group_choosed.setText(list.get(groupPosition).getSellerName());
        return convertView;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        if(convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.layout_child_item,parent,false);
        }
        CheckBox ck_child_choosed = convertView.findViewById(R.id.ck_child_choose);
        //商品图片
        ImageView iv_show_pic = convertView.findViewById(R.id.iv_show_pic);
        //商品主标题
        TextView tv_commodity_name = convertView.findViewById(R.id.tv_commodity_name);
        //商品副标题
        TextView tv_commodity_attr = convertView.findViewById(R.id.tv_commodity_attr);
        //商品价格
        TextView tv_commodity_price = convertView.findViewById(R.id.tv_commodity_price);
        //商品数量
        TextView tv_commodity_num = convertView.findViewById(R.id.tv_commodity_num);
        //商品减
        TextView iv_sub = convertView.findViewById(R.id.iv_sub);
        //商品加减中的数量变化
        final TextView tv_commodity_show_num = convertView.findViewById(R.id.tv_commodity_show_num);
        //商品加
        TextView iv_add = convertView.findViewById(R.id.iv_add);
        //删除按钮
        Button btn_commodity_delete = convertView.findViewById(R.id.btn_commodity_delete);

        //设置文本信息
        tv_commodity_name.setText(list.get(groupPosition).getList().get(childPosition).getTitle());
        tv_commodity_attr.setText(list.get(groupPosition).getList().get(childPosition).getSubhead());
        tv_commodity_price.setText("¥"+list.get(groupPosition).getList().get(childPosition).getPrice());
        tv_commodity_num.setText("x"+list.get(groupPosition).getList().get(childPosition).getNum());
        tv_commodity_show_num.setText(list.get(groupPosition).getList().get(childPosition).getNum()+"");
        String images = list.get(groupPosition).getList().get(childPosition).getImages();
        String[] urls = images.split("//|");
        Glide.with(context)
                .load(urls[0])
                .crossFade()
                .into(iv_show_pic);
        iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyGoodsItemNumberListener.doIncrease(groupPosition,childPosition,tv_commodity_show_num);
            }
        });
        iv_sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                modifyGoodsItemNumberListener.doDecrease(groupPosition,childPosition,tv_commodity_show_num);

            }
        });
        ck_child_choosed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //isChecked false  true
                checkGroupItemListener.checkChildItem(groupPosition,childPosition,((CheckBox)view).isChecked());
            }
        });
        if(list.get(groupPosition).getList().get(childPosition).isChildChoosed()){
            ck_child_choosed.setChecked(true);
        }else{
            ck_child_choosed.setChecked(false);
        }
        if(isEditor){
            btn_commodity_delete.setVisibility(View.VISIBLE);
        }else{
            btn_commodity_delete.setVisibility(View.GONE);
        }
        if(isEditor){
            btn_commodity_delete.setVisibility(View.VISIBLE);
        }else{
            btn_commodity_delete.setVisibility(View.GONE);
        }

        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    public interface CheckGroupItemListener{
        void checkGroupItem(int groupPosition,boolean isChecked);
        void checkChildItem(int groupPosition,int childPosition,boolean isChecked);
    }

    public interface ModifyGoodsItemNumberListener{
        void doIncrease(int groupPosition,int childPosition,View view);
        void doDecrease(int groupPosition,int childPosition,View view);
    }
}
view
package com.example.lenovo.myapplication.view;

import com.example.lenovo.myapplication.bean.DinDanBean;

import java.util.List;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public interface dindanviewinterface {
    void onFailed(String msg);

    void onSuccess(List<DinDanBean.DataBean> bean);
}
package com.example.lenovo.myapplication.view;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.example.lenovo.myapplication.R;
import com.example.lenovo.myapplication.adapter.Dindanadapter;
import com.example.lenovo.myapplication.bean.DinDanBean;
import com.example.lenovo.myapplication.presenter.DindanPresenter;

import java.util.List;

public class Main2Activity extends AppCompatActivity implements dindanviewinterface{
    private RecyclerView recycle;
    private List<DinDanBean.DataBean> list ;
    private Dindanadapter dindanadapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        recycle = findViewById(R.id.dindanrecycleview);
        dindanadapter = new Dindanadapter(this);
        recycle.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        recycle.setAdapter(dindanadapter);
        DindanPresenter presenter = new DindanPresenter(this);
        presenter.getdindan("71");
    }

    @Override
    public void onFailed(String msg) {

    }

    @Override
    public void onSuccess(List<DinDanBean.DataBean> bean) {
        this.list = bean;
        dindanadapter.setLiist(list);
    }
}

package com.example.lenovo.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;
import com.example.lenovo.myapplication.adapter.MyExpandAdapter;
import com.example.lenovo.myapplication.bean.ShopCarBean;
import com.example.lenovo.myapplication.presenter.Shoppresent;
import com.example.lenovo.myapplication.view.ShopView;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ShopView,MyExpandAdapter.ModifyGoodsItemNumberListener,MyExpandAdapter.CheckGroupItemListener{

    private List<ShopCarBean.DataBean> list;
    /**
     * 返回
     */
    private Button mBtnBack;
    /**
     * 编辑
     */
    private TextView mBtnEditor;
    private ExpandableListView mExpandList;

    /**
     * 全选
     */
    private CheckBox mBtnCheckAll;
    /**
     * 合计:¥0.00
     */
    private TextView mTvTotalPrice;
    /**
     * 结算(0)
     */
    private TextView mBtnAmount;
    private MyExpandAdapter adapter;
    private Shoppresent shoppresent;
    private int totalNum = 0;
    private double totalPrice= 0.00;
    private boolean flag;//默认是false

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //隐藏actionbar
        getSupportActionBar().hide();
        //去掉默认指示器
        mExpandList.setGroupIndicator(null);
        adapter = new MyExpandAdapter(this);
        mExpandList.setAdapter(adapter);
        shoppresent = new Shoppresent(this);
        shoppresent.getInfo("4601","android");
        adapter.setCheckGroupItemListener(this);
        adapter.setModifyGoodsItemNumberListener(this);

        mBtnCheckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isChoosedAll(((CheckBox)v).isChecked());
                statisticsPrice();
            }
        });
        //编辑
        mBtnEditor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!flag)
                {
                    flag = true;
                    mBtnEditor.setText("完成");
                    adapter.showDeleteButton(flag);
                }
                else
                {
                   flag = false;
                   mBtnEditor.setText("编辑");
                   adapter.showDeleteButton(flag);
                }
            }
        });
    }

    private void initView() {
        mBtnBack = (Button) findViewById(R.id.btnBack);
        mBtnEditor = (TextView) findViewById(R.id.btnEditor);
        mExpandList = (ExpandableListView) findViewById(R.id.expandList);
        mBtnCheckAll = (CheckBox) findViewById(R.id.btnCheckAll);
        mTvTotalPrice = (TextView) findViewById(R.id.tvTotalPrice);
        mBtnAmount = (TextView) findViewById(R.id.btnAmount);
    }

    private void defaultExpand(){
        for (int i = 0; i < adapter.getGroupCount();++i){
           mExpandList.expandGroup(i);
        }
    }
    @Override
    public void onSuccess(List<ShopCarBean.DataBean> o) {
           this.list = o;
           adapter.setList(list);
           defaultExpand();
    }
    @Override
    public void onError(String msg) {

    }

    @Override
    public void checkGroupItem(int groupPosition, boolean isChecked) {
        ShopCarBean.DataBean dataBean = list.get(groupPosition);
        dataBean.setGroupChoosed(isChecked);
        //遍历商家里面的商品,将其置为选中状态
        for (ShopCarBean.DataBean.ListBean listBean :dataBean.getList())
        {
            listBean.setChildChoosed(isChecked);
        }

        if (isCheckAll())
        {
            mBtnCheckAll.setChecked(true);
        }
        else {
            mBtnCheckAll.setChecked(false);
        }
        adapter.notifyDataSetChanged();
        statisticsPrice();
    }

    @Override
    public void checkChildItem(int groupPosition, int childPosition, boolean isChecked) {
        ShopCarBean.DataBean dataBean = list.get(groupPosition);//商家那一层
        List<ShopCarBean.DataBean.ListBean> listBeans = dataBean.getList();
        ShopCarBean.DataBean.ListBean listBean = listBeans.get(childPosition);
        //你点击商家的商品条目将其选中状态记录
        listBean.setChildChoosed(isChecked);
        //检测商家里面的每一个商品是否被选中,如果被选中,返回boolean
        boolean result = isGoodsCheckAll(groupPosition);
        if (result)
        {
           dataBean.setGroupChoosed(result);
        }
        else {
            dataBean.setGroupChoosed(result);
        }
        if (isCheckAll())
        {
            mBtnCheckAll.setChecked(true);
        }
        else {
            mBtnCheckAll.setChecked(false);
        }
        adapter.notifyDataSetInvalidated();
        statisticsPrice();

    }

    @Override
    public void doIncrease(int groupPosition, int childPosition, View view) {

        ShopCarBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition);
        int currentNum = listBean.getNum();
        currentNum++;
        //将商品数量设置在javabean上
        listBean.setNum(currentNum);
        adapter.notifyDataSetInvalidated();
        statisticsPrice();
    }

    @Override
    public void doDecrease(int groupPosition, int childPosition, View view) {
        ShopCarBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition);
        int currentNum = listBean.getNum();
        if (currentNum == 1)
        {
            return;
        }
        currentNum --;
        listBean.setNum(currentNum);
        adapter.notifyDataSetInvalidated();
        statisticsPrice();
    }

    private boolean isGoodsCheckAll (int groupPosition)
    {
        List<ShopCarBean.DataBean.ListBean> listBeans = this.list.get(groupPosition).getList();
        for (ShopCarBean.DataBean.ListBean listBean : listBeans)
        {
            if (listBean.isChildChoosed())
            {
                continue;
            }
            else {
                return false;
            }

        }
        return true;
    }
    //全选与反选
    private void isChoosedAll(boolean isChecked)
    {
        for (ShopCarBean.DataBean dataBean : list)
        {
            dataBean.setGroupChoosed(isChecked);
            for (ShopCarBean.DataBean.ListBean listBean : dataBean.getList())
            {
                listBean.setChildChoosed(isChecked);
            }
        }
        adapter.notifyDataSetChanged();
    }

    //购物车商品是否全部选中
    private boolean isCheckAll(){

        for (ShopCarBean.DataBean dataBean : list)
        {
            if (!dataBean.isGroupChoosed())
            {
                return  false;
            }
        }
        return true;
    }

    //计算你所选中的商品总价
    private void statisticsPrice(){
        totalNum = 0;
        totalPrice= 0.00;
        for (ShopCarBean.DataBean  dataBean :list)
        {
       for (ShopCarBean.DataBean.ListBean listBean : dataBean.getList())
       {
           if (listBean.isChildChoosed())
           {
               totalNum++;
             totalPrice = listBean.getNum()*listBean.getPrice();
           }
       }
        }
        mTvTotalPrice.setText("合计:¥"+totalPrice);
        mBtnAmount.setText("结算("+totalNum+")");
    }
}
package com.example.lenovo.myapplication.view;

import com.example.lenovo.myapplication.bean.ShopCarBean;

import java.util.List;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public interface ShopView {

    void onSuccess(List<ShopCarBean.DataBean> o);
    void onError(String msg);
}
presenter
package com.example.lenovo.myapplication.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.lenovo.myapplication.R;
import com.example.lenovo.myapplication.adapter.Dindanadapter;
import com.example.lenovo.myapplication.bean.DinDanBean;
import com.example.lenovo.myapplication.present.DindanPresenter;

import java.util.List;



/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public class dindan extends Fragment implements dindanviewinterface{

    private RecyclerView recycle;
 private List<DinDanBean.DataBean> list ;
    private Dindanadapter dindanadapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment2, container, false);
        recycle = view.findViewById(R.id.dindanrecycleview);
        dindanadapter = new Dindanadapter(getContext());
        recycle.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false));
        recycle.setAdapter(dindanadapter);
        DindanPresenter presenter = new DindanPresenter(this);
        presenter.getdindan("71");
        return view;
    }

    @Override
    public void onFailed(String msg) {

    }

    @Override
    public void onSuccess(List<DinDanBean.DataBean> bean) {
        this.list = bean;
        dindanadapter.setLiist(list);
    }
}
package com.example.lenovo.myapplication.present;

import com.example.lenovo.myapplication.bean.DinDanBean;

import java.util.List;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public interface Dindaninterface {
    void onFailed(String msg);

    void onSuccess(List<DinDanBean.DataBean> bean);
}

package com.example.lenovo.myapplication.presenter;

import com.example.lenovo.myapplication.bean.ShopCarBean;
import com.example.lenovo.myapplication.model.ShopModel;
import com.example.lenovo.myapplication.view.ShopView;

import java.util.List;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public class Shoppresent implements ShopPresenterface{

    private ShopView shopView;
    private  ShopModel model;
    public Shoppresent(ShopView shopView) {
        this.shopView = shopView;
        model = new ShopModel();
    }

    public void getInfo(String uid,String source)
    {
        model.shopcar(uid,source,this);
    }

    @Override
    public void onSuccess(List<ShopCarBean.DataBean> o) {
           shopView.onSuccess(o);
    }

    @Override
    public void onError(String msg) {
            shopView.onError(msg);
    }
}
package com.example.lenovo.myapplication.presenter;

import com.example.lenovo.myapplication.bean.ShopCarBean;

import java.util.List;

/**
 * 项目描述:
 * 作者:WangHao
 * 时期:
 */

public interface ShopPresenterface {
    void onSuccess(List<ShopCarBean.DataBean> o);
    void onError(String msg);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值