商城购物车的实现+MVP

先看看效果图
在这里插入图片描述

//首先要导入我们需要用到的依赖

    //okhttp3依赖
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    //gilde获取图片依赖
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    //解析数据gson
    implementation 'com.google.code.gson:gson:2.2.4'
//这是主页面的布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ExpandableListView
        android:id="@+id/able"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="60dp"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:background="#999999"
        android:gravity="center_vertical"
        >

        <CheckBox
            android:id="@+id/all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
           android:text="全选"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/price"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="合计:$0.00"
            android:padding="20dp"
            android:layout_weight="1"
            />

        <Button
            android:id="@+id/jiesuan"
            android:layout_width="100dp"
            android:layout_height="match_parent"
            android:text="去结算(0)" />
    </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="120dp"
    android:gravity="center_vertical"
    android:background="#E0E0E0"
    >
    <CheckBox
        android:id="@+id/child_cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/product_icon_iv"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_marginLeft="20dp"
        android:scaleType="centerCrop"
        android:src="@color/colorPrimary" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/product_title_name_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="2"
            android:text="商品标题" />

        <TextView
            android:id="@+id/product_price_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="¥0.0" />
    </LinearLayout>

     <com.example.gouwuche.MyAddSubView               (这里需要导入自己的包)
         android:id="@+id/add_remove_view"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginRight="10dp"
         />

</LinearLayout>

//这是主条目的布局文件
<?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="60dp"
    android:orientation="vertical"
    android:background="#fff"
    android:gravity="center_vertical"
    >

    <CheckBox
        android:id="@+id/seller_cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/seller_name_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp" />
</LinearLayout>

//实现加减自定义控件的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="2dp"
    android:layout_marginLeft="10dp"
    android:layout_width="60dp"
    android:layout_height="30dp"
    android:layout_gravity="center_vertical"
    android:background="#99000000"
    android:gravity="center_vertical">

    <TextView
        android:background="#ffffff"
        android:layout_weight="1"
        android:id="@+id/sub_tv"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="-"
        android:textSize="16sp" />

    <TextView
        android:text="1"
        android:layout_marginLeft="2dp"
        android:background="#ffffff"
        android:layout_weight="1"
        android:id="@+id/product_number_tv"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        />

    <TextView
        android:layout_marginLeft="2dp"
        android:background="#ffffff"
        android:layout_weight="1"
        android:id="@+id/add_tv"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="+"
        android:textSize="16sp" />

</LinearLayout>
//把接口的数据解析到一个类里
package com.example.gouwuche.bean;

import java.util.List;

public class Gouwu {
    /**
     * msg : 请求成功
     * code : 0
     * data : [{"list":[{"bargainPrice":99,.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":6,"price":7.99,"pscid":1,"selected":1,"sellerid":22,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家22","sellerid":"22"}]
     */

    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":99,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/4345173.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6037/35/2944615848/95178/6cd6cff0/594a3a10Na4ec7f39.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6607/258/1025744923/75738/da120a2d/594a3a12Ne3e6bc56.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6370/292/1057025420/64655/f87644e3/594a3a12N5b900606.jpg!q70.jpg","num":1,"pid":45,"price":2999,"pscid":39,"selected":0,"sellerid":1,"subhead":"高清双摄,就是清晰!2000+1600万高清摄像头,6GB大内存+高通骁龙835处理器,性能怪兽!","title":"一加手机5 (A5000) 6GB+64GB 月岩灰 全网通 双卡双待 移动联通电信4G手机"}]
         * sellerName : 商家1
         * sellerid : 1
         */

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

        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 : 99
             * createtime : 2017-10-14T21:38:26
             * detailUrl : https://item.m.jd.com/product/4345173.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends
             * images : https://m.360buyimg
             * num : 1
             * pid : 45
             * price : 2999
             * pscid : 39
             * selected : 0
             * sellerid : 1
             * subhead : 高清双摄,就是清晰!2000+1600万高清摄像头,6GB大内存+高通骁龙835处理器,性能怪兽!
             * title : 一加手机5 (A5000) 6GB+64GB 月岩灰 全网通 双卡双待 移动联通电信4G手机
             */

            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;

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

//封装的okhttp类

package com.example.gouwuche.utils;

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

import com.example.gouwuche.LoggingInterceptor;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Httputils {
    private final Handler mHandler;
    private final OkHttpClient mOkHttpClient;

    //////////////////////////////////////单例模式///////////////////////////////////////
    private static Httputils sHttputils;

    //构造方法不私有
    private Httputils(){
        //如果创建Handler的对象,是在一个普通的类里创建,那么一定要加上Looper.getMainLooper()这个参数
        mHandler = new Handler(Looper.getMainLooper());

        //添加拦截器
        LoggingInterceptor loggingInterceptor = new LoggingInterceptor();

        mOkHttpClient = new OkHttpClient.Builder()
                //调用.add方法
                .addInterceptor(loggingInterceptor)
                .readTimeout(2000,TimeUnit.SECONDS)
                .writeTimeout(2000,TimeUnit.SECONDS)
                .connectTimeout(2000,TimeUnit.SECONDS)
                .build();
    }

    //单例暴露一个普通的方法,给对方,双重锁模式
    public static Httputils getInstace(){
        if(sHttputils == null){
            synchronized (Httputils.class){
                if(sHttputils == null){
                    return sHttputils = new Httputils();
                }
            }
        }
        return sHttputils;
    }

    //接口回调
    public interface Onhttputils{
        void response(String str);

        void failual(Exception e);
    }

    //封装doget方法  用get方法进行解析
    public void doGet(String url,final Onhttputils onhttputils){
        Request request = new Request.Builder()
                .url(url)
                .build();

        Call call = mOkHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if(onhttputils != null){
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onhttputils.failual(e);
                        }
                    });
                }
            }

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

                final String str = response.body().string();
                if(onhttputils != null){
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onhttputils.response(str);
                        }
                    });
                }
            }
        });
    }

    //用post方法解析
    public void doPost(String url, Map<String,String> map, final Onhttputils onhttputils){
        FormBody.Builder builder = new FormBody.Builder();

        if(map != null){
            for (String key : map.keySet()) {
                builder.add(key,map.get(key));
            }
        }

        FormBody formBody = builder.build();

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

        Call call = mOkHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if(onhttputils != null){
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onhttputils.failual(e);
                        }
                    });
                }
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String str = response.body().string();
                if(onhttputils != null){
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onhttputils.response(str);
                        }
                    });
                }
            }
        });
    }
}


//自定义控件实现购物车加减

package com.example.gouwuche;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

//自定义控件实现加减效果
public class MyAddSubView extends LinearLayout implements View.OnClickListener {
    private int number = 1;
    private TextView sub_tv;
    private TextView product_number_tv;
    private TextView add_tv;

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

    public MyAddSubView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyAddSubView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View view = inflate(context, R.layout.zidingyi, this);

        sub_tv=view.findViewById(R.id.sub_tv);
        product_number_tv=view.findViewById(R.id.product_number_tv);
        add_tv=view.findViewById(R.id.add_tv);


        sub_tv.setOnClickListener(this);
        add_tv.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sub_tv:
                if (number > 1) {
                    --number;
                    product_number_tv.setText(number + "");
                    if (onNumberChangeListener != null) {
                        onNumberChangeListener.onNumberChange(number);
                    }
                } else {
                    Toast.makeText(getContext(), "不能再少了", Toast.LENGTH_SHORT).show();
                }
                break;


            case R.id.add_tv:
                ++number;
                product_number_tv.setText(number + "");
                if (onNumberChangeListener != null) {
                    onNumberChangeListener.onNumberChange(number);
                }
                break;
        }
    }


    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
        product_number_tv.setText(number + "");
    }
    
    //接口回调

    OnNumberChangeListener onNumberChangeListener;

    public void setOnNumberChangeListener(OnNumberChangeListener onNumberChangeListener) {
        this.onNumberChangeListener = onNumberChangeListener;
    }

    public interface OnNumberChangeListener {
        void onNumberChange(int num);
    }
}
//创建日志拦截器
package com.example.gouwuche;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 日志拦截器类,请求来了,先在这里进行处理,可以得到发请求到得到请求消耗多久的时间
 * 作用:可以排查网络请求速度慢的根本原因
 *  1.有可能是我们在请求网络时,客户端写了一堆业务逻辑
 *  2.有可能是服务器端,写的有问题
 *  3.有可能就是网速不给力
 */
public  class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        //拿到Request对象
        Request request = chain.request();

        long t1 = System.nanoTime();
        System.out.println(" request  = " + String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers()));

        //拿到Response对象
        Response response = chain.proceed(request);

        long t2 = System.nanoTime();
        //得出请求网络,到得到结果,中间消耗了多长时间
        System.out.println("response  " + String.format("Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        return response;
    }
}
//adapter适配器类

package com.example.gouwuche.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.gouwuche.MyAddSubView;
import com.example.gouwuche.R;
import com.example.gouwuche.bean.Gouwu;

import java.util.List;


public class MyAdapter extends BaseExpandableListAdapter {

    List<Gouwu.DataBean> list;

    public MyAdapter(List<Gouwu.DataBean> list) {
        this.list = list;
    }

    @Override
    public int getGroupCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return list.get(groupPosition).getList() == null ? 0 : list.get(groupPosition).getList().size();
    }

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

        Gouwu.DataBean dataBean = list.get(groupPosition);
        ParntViewHolder mParntViewHolder;
        if(convertView == null){
            convertView = View.inflate(parent.getContext(), R.layout.parnt,null);
            mParntViewHolder = new ParntViewHolder(convertView);
            convertView.setTag(mParntViewHolder);
        }else{
           mParntViewHolder = (ParntViewHolder) convertView.getTag();
        }
        mParntViewHolder.seller_cb.setText(dataBean.getSellerName());
        //根据当前商家的所有商品,确定该商家得checkbox是否被选中
        boolean currentSellerAllProductSelected = ischeckselect(groupPosition);
        //更新UI
        mParntViewHolder.seller_cb.setChecked(currentSellerAllProductSelected);

        //设置商家的点击事件
       mParntViewHolder.seller_cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击商家得checkBox
                if (onCartListChangeListener != null) {
                    onCartListChangeListener.onSellerCheckedChange(groupPosition);
                }
            }
        });
        return convertView;
    }

    private class ParntViewHolder {
        public CheckBox seller_cb;
        public TextView seller_name_tv;

        public ParntViewHolder(View rootView) {
            this.seller_cb = (CheckBox) rootView.findViewById(R.id.seller_cb);
            this.seller_name_tv = (TextView) rootView.findViewById(R.id.seller_name_tv);
        }
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        List<Gouwu.DataBean.ListBean> listBean = this.list.get(groupPosition).getList();
        Gouwu.DataBean.ListBean bean = listBean.get(childPosition);
        final ChildViewHolder mChildViewHolder;
        if(convertView == null){
            convertView = View.inflate(parent.getContext(),R.layout.child,null);
            mChildViewHolder = new ChildViewHolder(convertView);
            convertView.setTag(mChildViewHolder);
        }else{
            mChildViewHolder = (ChildViewHolder) convertView.getTag();
        }


        //获取到图片
        String images = listBean.get(childPosition).getImages();

        //截取图片数据
        String[] split = images.split("!");
        //获取到第一张图片
        Glide.with(parent.getContext()).load(split[0]).into(mChildViewHolder.product_icon_iv);

        //设置商品名字
        mChildViewHolder.product_title_name_tv.setText(bean.getTitle());
        //设置商品单价
        mChildViewHolder.product_price_tv.setText(bean.getPrice()+"");
        //设置复选框是否选中
        mChildViewHolder.child_cb.setChecked(bean.getSelected() == 1);
        //设置组合式自定义控件内部的数量
        mChildViewHolder.add_remove_view.setNumber(bean.getNum());

        mChildViewHolder.child_cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onCartListChangeListener != null){
                    onCartListChangeListener.onProductCheckedChange(groupPosition,childPosition);
                }
            }
        });

        mChildViewHolder.add_remove_view.setOnNumberChangeListener(new MyAddSubView.OnNumberChangeListener() {
            @Override
            public void onNumberChange(int num) {
                if (onCartListChangeListener != null) {
                    onCartListChangeListener.onProductNumberChange(groupPosition, childPosition, num);
                }
            }
        });
        return convertView;
    }

    //当前商家所有商品是否被选中
    public boolean ischeckselect(int groupPosition){
        Gouwu.DataBean dataBean = list.get(groupPosition);

        List<Gouwu.DataBean.ListBean> data = dataBean.getList();

        for (Gouwu.DataBean.ListBean listdata : data) {
            if(listdata.getSelected() == 0){
                return false;
            }
        }
        return true;
    }


    //所有商品是否被选中,双重for循环,里面的集合套集合取数据
    public boolean isAllProductsSelected() {
        for (int i = 0; i < list.size(); i++) {
            Gouwu.DataBean dataBean = list.get(i);
            List<Gouwu.DataBean.ListBean> list1 = dataBean.getList();
            for (int j = 0; j <  list1.size(); j++) {
                if (list1.get(j).getSelected() == 0) {
                    return false;
                }
            }
        }
        return true;
    }




    //计算总的数量
    public int allNumber(){
        int number = 0;
        for (int i = 0; i < list.size(); i++) {
            Gouwu.DataBean dataBean = list.get(i);
            List<Gouwu.DataBean.ListBean> data = dataBean.getList();
            for (int j = 0; j < data.size(); j++) {
                if(data.get(j).getSelected() == 1){
                     int num = data.get(j).getNum();
                     number += num;
                }
            }
        }
        return number;
    }

    //计算总价
    public float allPrice(){
        float price = 0;
        for (int i = 0; i < list.size(); i++) {
            Gouwu.DataBean dataBean = list.get(i);
            List<Gouwu.DataBean.ListBean> data = dataBean.getList();
            for (int j = 0; j < data.size(); j++) {
                if(data.get(j).getSelected() == 1){
                    int num = data.get(j).getNum();
                    float mprice = data.get(j).getPrice();
                    price += num*mprice;
                }
            }
        }
        return price;
    }

    //当商家得checkbox被点击得时候调用,设置当前商家得所有商品得状态--------商家组其所有的商品
    public void  setcheckzhuangtai(int grouposition, boolean isSelected){
        Gouwu.DataBean dataBean = list.get(grouposition);
        List<Gouwu.DataBean.ListBean> data = dataBean.getList();
        for (int i = 0; i <data.size() ; i++) {
            Gouwu.DataBean.ListBean listBean = data.get(i);
            listBean.setSelected(isSelected ? 1 : 0);
        }
    }

    //当商品子条目得checkbox被点击得时候调用,改变当前商品状态---------商品子条目
    public void setshangpin(int groupPosition, int childPosition){
        Gouwu.DataBean dataBean = list.get(groupPosition);
        List<Gouwu.DataBean.ListBean> data = dataBean.getList();
        Gouwu.DataBean.ListBean listBean = data.get(childPosition);
        listBean.setSelected(listBean.getSelected() == 0 ?1 : 0 );
    }

    //设置所有商品得状态
    public void  allshangpin(boolean selected){
        for (int i = 0; i < list.size(); i++) {
            Gouwu.DataBean dataBean = list.get(i);
            List<Gouwu.DataBean.ListBean> list1 = dataBean.getList();
            for (int j = 0; j < list1.size(); j++) {
                list1.get(j).setSelected(selected?1:0);
            }
        }
    }

    //当加减器被点击得时候调用,改变当前商品得数量
    public void changeCurrentProductNumber(int groupPosition, int childPosition, int number) {
        Gouwu.DataBean dataBean = list.get(groupPosition);
        List<Gouwu.DataBean.ListBean> listBeans = dataBean.getList();
        Gouwu.DataBean.ListBean listBean = listBeans.get(childPosition);
        listBean.setNum(number);
    }


    private class ChildViewHolder {
        public CheckBox child_cb;
        public ImageView product_icon_iv;
        public TextView product_title_name_tv;
        public TextView product_price_tv;
        public MyAddSubView add_remove_view;

        public ChildViewHolder(View rootView) {
            this.child_cb = (CheckBox) rootView.findViewById(R.id.child_cb);
            this.product_icon_iv = (ImageView) rootView.findViewById(R.id.product_icon_iv);
            this.product_title_name_tv = (TextView) rootView.findViewById(R.id.product_title_name_tv);
            this.product_price_tv = (TextView) rootView.findViewById(R.id.product_price_tv);
            this.add_remove_view = (MyAddSubView) rootView.findViewById(R.id.add_remove_view);
        }
    }


    //定义一个假对象
    onCartListChangeListener onCartListChangeListener;

    //暴露一个方法供他们使用
    public void setOnCartListChangeListener(MyAdapter.onCartListChangeListener onCartListChangeListener) {
        this.onCartListChangeListener = onCartListChangeListener;
    }

    //实现一个接口
    public interface onCartListChangeListener {

        void onSellerCheckedChange(int groupPosition);

        void onProductCheckedChange(int groupPosition, int childPosition);

        void onProductNumberChange(int groupPosition, int childPosition, int number);
    }


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

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return null;
    }

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

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

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


}


//Mainactivity
package com.example.gouwuche;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.example.gouwuche.adapter.MyAdapter;
import com.example.gouwuche.bean.Gouwu;
import com.example.gouwuche.presenter.Presenter;
import com.example.gouwuche.utils.Httputils;
import com.google.gson.Gson;

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


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ExpandableListView able;
    private CheckBox all;
    private TextView price;
    private Button jiesuan;
    Presenter presenter = new Presenter();
    MyAdapter ma;
    String url = "http://www.zhaoapi.cn/product/getCarts";


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

        initData();

    }

    private void initData() {

        HashMap<String,String> map = new HashMap<>();
        map.put("uid","71");

        //创建presenter层 new 一个实例
       

        //调用里面设置的方法
        presenter.Hzjpresenter(url, map, new Presenter.HzjInterface() {
            @Override//成功方法
            public void success(List<Gouwu.DataBean> data) {

                    ma = new MyAdapter(data);

                    //调用adapter里的接口回调给的方法
                    ma.setOnCartListChangeListener(new MyAdapter.onCartListChangeListener() {
                        @Override//点击商家的CheckBox的回调
                        public void onSellerCheckedChange(int groupPosition) {
                            //商家被点击
                            boolean ischeckselect = ma.ischeckselect(groupPosition);
                            ma.setcheckzhuangtai(groupPosition,!ischeckselect);
                            ma.notifyDataSetChanged();
                            //B.刷新底部数据
                            refreshselect();
                        }
                        //点击商品的CheckBox的回调
                        @Override
                        public void onProductCheckedChange(int groupPosition, int childPosition) {
                            ma.setshangpin(groupPosition,childPosition);
                            ma.notifyDataSetChanged();
                            //B.刷新底部数据
                            refreshselect();
                        }
                        //点击加减按钮的回调
                        @Override
                        public void onProductNumberChange(int groupPosition, int childPosition, int number) {
                            ma.changeCurrentProductNumber(groupPosition,childPosition,number);
                            ma.notifyDataSetChanged();
                            //B.刷新底部数据
                            refreshselect();
                        }
                    });
                    //设置适配器
                    able.setAdapter(ma);
                    //去掉箭头
                    able.setGroupIndicator(null);
                    for(int x=0; x<data.size(); x++){
                        able.expandGroup(x);
                    }
                    //调用刷新方法
                    refreshselect();
            }

            @Override//失败方法
            public void failed() {

            }
        });


    }



    //刷新总价方法
    private void refreshselect() {
        //去判断是否所有得商品都被选中
        boolean allProductsSelected = ma.isAllProductsSelected();
        //设置给全选checkBox
        all.setChecked(allProductsSelected);
        //计算总价
        float v = ma.allPrice();
        price.setText("总价:"+v);
        //计算总数量
        int totalNumber = ma.allNumber();
        jiesuan.setText("去结算(" + totalNumber + ")");

    }

    @Override
    public void onClick(View v) {

    }

    private void initView() {
        able = (ExpandableListView) findViewById(R.id.able);
        all = (CheckBox) findViewById(R.id.all);
        price = (TextView) findViewById(R.id.price);
        jiesuan = (Button) findViewById(R.id.jiesuan);
        jiesuan.setOnClickListener(this);

        //全选按钮的点击事件
        all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean allProductsSelected = ma.isAllProductsSelected();
                ma.allshangpin(!allProductsSelected);
                ma.notifyDataSetChanged();
                //刷新底部数据
                refreshselect();
            }
        });
    }
    //避免内存泄漏
    @Override
    protected void onDestroy() {
        super.onDestroy();
        
         presenter = null;
    }
}
//创建一个presenter层

package com.example.gouwuche.presenter;

import com.example.gouwuche.bean.Gouwu;
import com.example.gouwuche.utils.Httputils;
import com.google.gson.Gson;

import java.util.List;
import java.util.Map;
 
public class Presenter {
                                                                   //把接口传进来             
    public void Hzjpresenter(String url, Map<String,String> map,final HzjInterface hzjInterface){
        Httputils httputils = Httputils.getInstace();

        //获取封装okhttp中调用dopost方法
        httputils.doPost(url, map, new Httputils.Onhttputils() {
            @Override
            public void response(String str) {
                Gouwu gouwu = new Gson().fromJson(str, Gouwu.class);
                List<Gouwu.DataBean> data = gouwu.getData();
                //调用接口中成功方法
                hzjInterface.success(data);
            }
            @Override
            public void failual(Exception e) {
            }
        });
    }

    //实现接口,里面返回两个方法
    public interface HzjInterface{
        //成功方法
        void success(List<Gouwu.DataBean> data);
        //失败
        void failed();
    }
}

猜你喜欢

转载自blog.csdn.net/NorthHar/article/details/84317804