retrofit+rxjava + okhttp +mvp 购物车

分包的情况
retrofit+rxjava + okhttp +mvp 购物车_第1张图片
1. 依赖

//添加retrofit依赖
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    //添加gson转换器的依赖
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
//RXJava的依赖
    compile "io.reactivex.rxjava2:rxjava:2.1.10"
//RXJava安卓的依赖
    compile 'io.reactivex.rxjava2:rxandroid:2.0.2'

    //注意 rxjava2是2.0的 不加2表示的是1.0
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
//butterknife
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    implementation 'com.facebook.fresco:fresco:1.8.1'
2.utils包
   1.)tonstans类  -------->接口
public class Constant {
    public  static  String  baseUrl="http://120.27.23.105/";
    //查询购物车
    public static  String   seleteUrl="product/getCarts";
  public  static   String   updetaUrl="product/updateCarts";
    public  static   String   deleteUrl="product/deleteCart";
}

2.) ApiService 类

public interface ApiService {
    @GET("{url}")
    ObservabledoGet(@Path(value = "url",encoded = true)String url);
    @GET("{url}")
    ObservabledoGet(@Path(value = "url",encoded = true)String url, @QueryMap Mapmap);

}

3.)
RetrofitUtil 类 ——->请求数据的工具类

public class RetrofitUtil {
 private static RetrofitUtil retrofitUtil = null;
    private Retrofit retrofit;

    private RetrofitUtil() {
    }

    private RetrofitUtil(String baseUrl) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //.addNetworkInterceptor()//网络拦截器
                .addInterceptor(new CommonParamsInterceptor())//拦截器
                //.connectTimeout()//连接超时
                .build();


        //创建retrofit
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())//添加转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//设置支持rxjava 注意是2
                .build();
    }

    /**
     * 单例模式
     * @return
     */
    public static RetrofitUtil getInstance(String baseUrl) {
        if (retrofitUtil == null) {
            synchronized (RetrofitUtil.class) {
                if (retrofitUtil == null) {
                    retrofitUtil = new RetrofitUtil(baseUrl);
                }
            }
        }

        return retrofitUtil;
    }

    public  T createService(Class service) {
        return retrofit.create(service);
    }

    public static ApiService getService() {
        return RetrofitUtil.getInstance(Constant.baseUrl).createService(ApiService.class);
    }

    /**
     * 公共参数的拦截器
     */
    private static class CommonParamsInterceptor implements Interceptor {

        //intercept方法就是拦截的意思....拦截的是一个请求,,,一旦拦截之后可以对请求的参数进行处理
        //Chain chain 链条的意思
        @Override
        public Response intercept(Chain chain) throws IOException {



            //调用request()方法得到拦截的请求
            Request request = chain.request();

            //获取请求的方式
            String method = request.method();//GET POST
            //拦截的请求的路径
            String oldUrl = request.url().toString();

            Log.e("----oldUrl",oldUrl);


            //要添加的公共参数...map
            Map map = new HashMap<>();
            map.put("source","android");



            if ("GET".equals(method)){
                StringBuilder stringBuilder = new StringBuilder();//创建一个stringBuilder...字符串缓冲区

                stringBuilder.append(oldUrl);

                if (oldUrl.contains("?")){
                    //?在最后面....2类型
                    if (oldUrl.indexOf("?") == oldUrl.length()-1){

                    }else {
                        //3类型...拼接上&
                        stringBuilder.append("&");
                    }
                }else {
                    //不包含? 属于1类型,,,先拼接上?号
                    stringBuilder.append("?");
                }

                //添加公共参数....source=android&appVersion=100&
                for (Map.Entry entry: map.entrySet()) {
                    //拼接
                    stringBuilder.append(entry.getKey())
                            .append("=")
                            .append(entry.getValue())
                            .append("&");
                }

                //删掉最后一个&符号
                if (stringBuilder.indexOf("&") != -1){
                    stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
                }
                //得到含有公共参数的新路径.....使用新路径去请求
                String newUrl = stringBuilder.toString();

                Log.e("----newUrl",newUrl);

                //新的路径构建一个新的请求
                request = request.newBuilder().url(newUrl).build();

            }else if ("POST".equals(method)){

                //参数在请求的实体内容上....拿到以前的参数,把以前的参数和公共参数全都添加到请求实体上
                RequestBody requestBody = request.body();
                if (requestBody instanceof FormBody){//前边是不是后边的子类/实例对象
                    FormBody oldBody = (FormBody) requestBody;//keywords...page

                    FormBody.Builder builder = new FormBody.Builder();

                    //先添加之前的参数
                    for (int i = 0;i//键值对的形式添加
                        builder.add(oldBody.name(i),oldBody.value(i));
                    }
                    //添加公共参数
                    for (Map.Entry entry: map.entrySet()) {

                        builder.add(entry.getKey(),entry.getValue());

                    }

                    //构建一个新的请求
                    request = request.newBuilder().url(oldUrl).post(builder.build()).build();


                }

            }


            //执行请求 获取到响应
            Response response = chain.proceed(request);
            return response;
        }
    }

    /**
     * 接口地址:http://www.bwstudent.com/kjbd/user/modifyImg

     接口交互:POST

     接口描述:上传用户的头像

     FormParam入参

         Parameter 类型 描述 例子
         img   String 图片 需要上传的图片路径
     head入参

     Parameter 类型 描述 例子
         ak    string 版本号    001002003
         userId    int    用户id   1
         sessionId string 用户状态   201801301

     ------------封装header的拦截器....注意封装的是不变的head头信息



     */

}

4.)自定义二级列表的类

public class MyExpanableListView extends ExpandableListView {
    public MyExpanableListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //高度
        int height = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);

        super.onMeasure(widthMeasureSpec, height);
    }
}

2.bean包
1.)cartbean

public class CartBean {


    /**
     * code : 0
     * data : [{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.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":6,"pid":10,"price":555.55,"pscid":1,"selected":1,"sellerid":3,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家3","sellerid":"3"},{"list":[{"bargainPrice":159,"createtime":"2017-10-14T21:49:15","detailUrl":"https://item.m.jd.com/product/5061723.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t8716/197/1271594444/173291/2f40bb4f/59b743bcN8509428e.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8347/264/1286771527/92188/5cf5ec04/59b7420fN65378e9e.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7363/165/3000956253/190883/179a372/59b743bfNd0c79d93.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7399/112/2935531768/183594/b77c7d4a/59b7441aNc3d40133.jpg!q70.jpg","num":6,"pid":98,"price":1900,"pscid":112,"selected":0,"sellerid":9,"subhead":"针织针织闪闪闪亮你的眼","title":"维迩旎 2017秋冬新款长袖针织连衣裙韩版气质中长款名媛包臀A字裙 zx179709 黑色 XL"}],"sellerName":"商家9","sellerid":"9"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.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":18,"price":399,"pscid":1,"selected":0,"sellerid":11,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"},{"bargainPrice":159,"createtime":"2017-10-14T21:49:15","detailUrl":"https://item.m.jd.com/product/5061723.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t8716/197/1271594444/173291/2f40bb4f/59b743bcN8509428e.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8347/264/1286771527/92188/5cf5ec04/59b7420fN65378e9e.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7363/165/3000956253/190883/179a372/59b743bfNd0c79d93.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7399/112/2935531768/183594/b77c7d4a/59b7441aNc3d40133.jpg!q70.jpg","num":1,"pid":100,"price":2200,"pscid":112,"selected":0,"sellerid":11,"subhead":"针织针织闪闪闪亮你的眼","title":"维迩旎 2017秋冬新款长袖针织连衣裙韩版气质中长款名媛包臀A字裙 zx179709 黑色 XL"}],"sellerName":"商家11","sellerid":"11"},{"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":75,"price":36999,"pscid":40,"selected":0,"sellerid":19,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"},{"bargainPrice":111.99,"createtime":"2017-10-03T23:53:28","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.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":3,"pid":3,"price":198,"pscid":1,"selected":0,"sellerid":19,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家19","sellerid":"19"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.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":4,"price":999,"pscid":1,"selected":0,"sellerid":20,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家20","sellerid":"20"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.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":4,"pid":5,"price":88.99,"pscid":1,"selected":0,"sellerid":21,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家21","sellerid":"21"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-03T23:53:28","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.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":3,"pid":6,"price":7.99,"pscid":1,"selected":0,"sellerid":22,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家22","sellerid":"22"}]
     * msg : 请求成功
     */

    private String code;
    private String msg;
    private List data;

    public String getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

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

    public List getData() {
        return data;
    }

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

    public static class DataBean {
        /**
         * list : [{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.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":6,"pid":10,"price":555.55,"pscid":1,"selected":1,"sellerid":3,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}]
         * sellerName : 商家3
         * sellerid : 3
         */
        private boolean groupChecked;


        public boolean isGroupChecked() {
            return groupChecked;
        }


        public void setGroupChecked(boolean groupChecked) {
            this.groupChecked = groupChecked;
        }


        private String sellerName;
        private String sellerid;
        private List 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 getList() {
            return list;
        }

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

        public static class ListBean {
            /**
             * bargainPrice : 111.99
             * createtime : 2017-10-14T21:39:05
             * detailUrl : https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends
             * images : https://m.360buyimg.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 : 6
             * pid : 10
             * price : 555.55
             * pscid : 1
             * selected : 1
             * sellerid : 3
             * subhead : 每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下
             * title : 北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g
             */

            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;

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

2.)
CountPriceBean类

public class CountPriceBean {
    private String priceString;
    private int count;

    public CountPriceBean(String priceString, int count) {
        this.priceString = priceString;
        this.count = count;
    }

    public String getPriceString() {
        return priceString;
    }

    public void setPriceString(String priceString) {
        this.priceString = priceString;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

3.model包

1.)
BaseModel
public interface BaseModel {
    void  getCartData(String seleteUrl);
    void unsubcribe();
}
2.)
MainModel类

public class MainModel implements  BaseModel{
    private  Ipersenter ipersenter;
    private Disposable d;

    public MainModel(Ipersenter ipersenter) {
        this.ipersenter=ipersenter;
    }
    @Override
    public void getCartData(String seleteUrl) {
        Map map=new HashMap<>();
        map.put("uid","98");
        RetrofitUtil.getService().doGet(seleteUrl,map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        MainModel.this.d=d;
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                     ipersenter.onSuccess(responseBody);
                    }

                    @Override
                    public void onError(Throwable e) {
                        ipersenter.onError(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void unsubcribe() {
    d.dispose();//解除订阅
    }
}

4.) persenter包

1.)
BasePresenter类

public class BasePresenter {
protected Reference mViewRef;//View接口类型弱引用
public void attachView(T view) {
mViewRef = new WeakReference(view); //建立关联
}
protected T getView() {
return mViewRef.get();//获取View
}
public boolean isViewAttached() {//判断是否与View建立了关联
return mViewRef != null && mViewRef.get() != null;
}
public void detachView() {//解除关联
if (mViewRef != null) {
mViewRef.clear();
mViewRef = null;
}
}
}

2.)
Ipersenter类

public interface Ipersenter {
void getCartData(String seleteUrl);
void unsubcribe();
void onSuccess(ResponseBody responseBody);
void onError(Throwable throwable);
}

3.)MainPersenter类

public class MainPersenter extends BasePresenter implements Ipersenter{
private MainModel mainModel;
private Imain imain;
public MainPersenter(Imain imain) {
this.imain=imain;
mainModel = new MainModel(this);
}
public void getCartData(String seleteUrl) {
mainModel.getCartData(seleteUrl);
}
@Override
public void unsubcribe() {
mainModel.unsubcribe();
}
@Override
public void onSuccess(ResponseBody responseBody) {
imain.onSuccess(responseBody);
}
@Override
public void onError(Throwable throwable) {
imain.onError(throwable);
}
}

5.view包
1.)IMain类--->接口

public interface Imain {
void onSuccess(ResponseBody responseBody);
void onError(Throwable throwable);
}

2.)
MainActivity类

public class MainActivity extends Activity implements Imain ,View.OnClickListener{
@BindView(R.id.expan_view)
MyExpanableListView expanView;
@BindView(R.id.relative_progress)
RelativeLayout relativeProgress;
@BindView(R.id.check_all)
CheckBox checkAll;
@BindView(R.id.text_total)
TextView textTotal;
@BindView(R.id.text_buy)
TextView textBuy;
private MainPersenter mainPersenter;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == 0){
CountPriceBean countPriceBean = (CountPriceBean) msg.obj;
//设置价格和数量
textTotal.setText(“合计:¥”+countPriceBean.getPriceString());
textBuy.setText(“去结算(“+countPriceBean.getCount()+”)”);
}
}
};
private MyAdapter myAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //自定义标题
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    //设置标题为某个layout
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);

    //去掉默认的指示器
    expanView.setGroupIndicator(null);
    //创建中间者persenter
    mainPersenter = new MainPersenter(this);
    checkAll.setOnClickListener(this);
}

@Override
protected void onResume() {
    super.onResume();
    //显示进度条
    relativeProgress.setVisibility(View.VISIBLE);
    //调用获取数据的方法


    mainPersenter.getCartData(Constant.seleteUrl);
}



@Override
public void onSuccess(ResponseBody responseBody) {
    try {
        String json = responseBody.string();
        Log.v("bean","数据++++++++++"+json);
        CartBean cartBean=new Gson().fromJson(json,CartBean.class);

        //获取数据成功...隐藏
        relativeProgress.setVisibility(View.GONE);
        if (cartBean!=null){
            //cartBean再设置奢配器之前需不需要改变数据
            //1.在bean类中添加商家是否选中的字段....默认值的false,初始值是根据该组下面所有孩子的状态进行改变的
            for (int i = 0;i listBeans = cartBean.getData().get(i).getList();
                //设置组的初始选中状态,,,,根据所有孩子的状态
                cartBean.getData().get(i).setGroupChecked(isAllChildInGroupChecked(listBeans));
            }


            //2.根据所有商家选中的状态,改变全选的状态
            checkAll.setChecked(isAllGroupChecked(cartBean));
            //设置适配器
            myAdapter = new MyAdapter(MainActivity.this, cartBean, handler, relativeProgress, mainPersenter);
            expanView.setAdapter(myAdapter);


            //展开所有的组...expanableListView.expandGroup()
            for (int i = 0;i listBeans) {


    for (int i=0;i

}

3.)myadapter类

public class MyAdapter extends BaseExpandableListAdapter {
private MainPersenter mainPresenter;
private RelativeLayout relative_progress;
private Handler handler;
private CartBean cartBean;
private Context context;
private int childIndex;
private int allIndex;

public MyAdapter(Context context, CartBean cartBean, Handler handler, RelativeLayout relative_progress, MainPersenter mainPresenter) {
    this.context = context;
    this.cartBean = cartBean;
    this.handler = handler;
    this.relative_progress = relative_progress;
    this.mainPresenter = mainPresenter;
}

@Override
public int getGroupCount() {
    return cartBean.getData().size();
}

@Override
public int getChildrenCount(int i) {
    return cartBean.getData().get(i).getList().size();
}

@Override
public Object getGroup(int i) {
    return cartBean.getData().get(i);
}

@Override
public Object getChild(int i, int i1) {
    return cartBean.getData().get(i).getList().get(i1);
}

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

@Override
public long getChildId(int i, int i1) {
    return i1;
}

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

@Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
    final GroupHolder holder;
    if (view == null) {
        view = View.inflate(context, R.layout.group_layout, null);
        holder = new GroupHolder(view);
        view.setTag(holder);
    } else {
        holder = (GroupHolder) view.getTag();
    }


    final CartBean.DataBean dataBean = cartBean.getData().get(i);
    //赋值
    holder.groupText.setText(dataBean.getSellerName());
    holder.groupCheck.setChecked(dataBean.isGroupChecked());
    holder.groupCheck.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //显示progress
            relative_progress.setVisibility(View.VISIBLE);


            //根据商家的状态holder.checkbox.ischecked(),改变下面所有子条目的状态,,,10,,改变十次,更新完成一个之后再去执行下一个...递归
            childIndex = 0;
            updateAllChildInGroup(dataBean, holder.groupCheck.isChecked());

        }


    });
    return view;
}

@Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
    ChildHolder holder;
    if (view == null){
        view = View.inflate(context, R.layout.child_layout,null);
        holder = new ChildHolder(view);

        view.setTag(holder);
    }else {
        holder = (ChildHolder) view.getTag();
    }


    final CartBean.DataBean.ListBean listBean = cartBean.getData().get(i).getList().get(i1);


    //赋值
    holder.childTitle.setText(listBean.getTitle());
    holder.childPrice.setText("¥"+listBean.getBargainPrice());


    String[] strings = listBean.getImages().split("\|");
     holder.childImage.setImageURI(strings[0]);


    holder.childCheck.setChecked(listBean.getSelected() == 0? false:true);//根据0,1进行设置是否选中
    //setText()我们使用一定是设置字符串
    holder.textNum.setText(listBean.getNum()+"");


    //点击事件
    holder.childCheck.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //此时需要显示进度条
            relative_progress.setVisibility(View.VISIBLE);
            //更新购物车,,,,需要改变是否选中,,,如果现在显示的是0,改成1;;;1--->0


            Map params = new HashMap<>();


            //?uid=71&sellerid=1&pid=1&selected=0&num=10
            params.put("uid","98");
            params.put("sellerid", String.valueOf(listBean.getSellerid()));
            params.put("pid", String.valueOf(listBean.getPid()));


            params.put("selected", String.valueOf(listBean.getSelected() == 0? 1:0));
            params.put("num", String.valueOf(listBean.getNum()));
            RetrofitUtil.getService().doGet(Constant.updetaUrl,params)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(ResponseBody responseBody) {
                            mainPresenter.getCartData(Constant.seleteUrl);
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });



        }
    });


    //加号
    holder.textAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //此时需要显示进度条
            relative_progress.setVisibility(View.VISIBLE);
            //更新购物车,,,,需要改变是数量,,,,需要加1


            Map params = new HashMap<>();


            //?uid=71&sellerid=1&pid=1&selected=0&num=10
            params.put("uid","98");
            params.put("sellerid", String.valueOf(listBean.getSellerid()));
            params.put("pid", String.valueOf(listBean.getPid()));
            params.put("selected", String.valueOf(listBean.getSelected()));


            params.put("num", String.valueOf(listBean.getNum()+1));

            RetrofitUtil.getService().doGet(Constant.updetaUrl,params)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(ResponseBody responseBody) {
                            mainPresenter.getCartData(Constant.seleteUrl);
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });



        }
    });
    //减号
    holder.textJian.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int num = listBean.getNum();


            if (num == 1){
                return;
            }


            //此时需要显示进度条
            relative_progress.setVisibility(View.VISIBLE);
            //更新购物车,,,,需要改变是数量,,,,需要加1


            Map params = new HashMap<>();


            //?uid=71&sellerid=1&pid=1&selected=0&num=10
            params.put("uid","98");
            params.put("sellerid", String.valueOf(listBean.getSellerid()));
            params.put("pid", String.valueOf(listBean.getPid()));
            params.put("selected", String.valueOf(listBean.getSelected()));


            params.put("num", String.valueOf(num-1));
            RetrofitUtil.getService().doGet(Constant.updetaUrl,params)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(ResponseBody responseBody) {
                            mainPresenter.getCartData(Constant.seleteUrl);
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });



        }
    });
    //删除
    holder.textDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //显示进度条
            relative_progress.setVisibility(View.VISIBLE);
            //调用删除的接口
            Map params = new HashMap<>();


            //uid=72&pid=1
            params.put("uid","98");
            params.put("pid", String.valueOf(listBean.getPid()));

            RetrofitUtil.getService().doGet(Constant.deleteUrl,params)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(ResponseBody responseBody) {
                            mainPresenter.getCartData(Constant.seleteUrl);
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });



        }
    });


    return view;
}

private void updateAllChildInGroup(final CartBean.DataBean dataBean, final boolean checked) {
    CartBean.DataBean.ListBean listBean = dataBean.getList().get(childIndex);


    Map params = new HashMap<>();


    //?uid=71&sellerid=1&pid=1&selected=0&num=10
    params.put("uid", "98");
    params.put("sellerid", String.valueOf(listBean.getSellerid()));
    params.put("pid", String.valueOf(listBean.getPid()));


    params.put("selected", String.valueOf(checked ? 1 : 0));
    params.put("num", String.valueOf(listBean.getNum()));
    RetrofitUtil.getService().doGet(Constant.updetaUrl, params)
            .observeOn(Schedulers.io())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(ResponseBody responseBody) {
                    //索引增加
                    childIndex++;
                    if (childIndex < dataBean.getList().size()) {
                        //再去更新下一条
                        updateAllChildInGroup(dataBean, checked);


                    } else {//全都更新完成了....重新查询购物车
                        mainPresenter.getCartData(Constant.seleteUrl);
                    }
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
}



@Override
public boolean isChildSelectable(int i, int i1) {
    return true;
}

static class GroupHolder {
    @BindView(R.id.group_check)
    CheckBox groupCheck;
    @BindView(R.id.group_text)
    TextView groupText;

    GroupHolder(View view) {
        ButterKnife.bind(this, view);
    }
}

static class ChildHolder {
    @BindView(R.id.child_check)
    CheckBox childCheck;
    @BindView(R.id.child_image)
    SimpleDraweeView childImage;
    @BindView(R.id.child_title)
    TextView childTitle;
    @BindView(R.id.child_price)
    TextView childPrice;
    @BindView(R.id.text_jian)
    TextView textJian;
    @BindView(R.id.text_num)
    TextView textNum;
    @BindView(R.id.text_add)
    TextView textAdd;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.text_delete)
    TextView textDelete;

    ChildHolder(View view) {
        ButterKnife.bind(this, view);
    }
}
/**
 * 计算总价和数量,,,并且发送给activity进行显示
 */
public void sendPriceAndCount() {


    double price = 0;
    int count = 0;


    for (int i = 0;i listBeans = cartBean.getData().get(i).getList();
        for (int j = 0; j< listBeans.size(); j++){


            if (listBeans.get(j).getSelected() == 1){
                price += listBeans.get(j).getBargainPrice() * listBeans.get(j).getNum();
                count += listBeans.get(j).getNum();
            }
        }
    }


    //double高精度,,,计算的时候可能会出现一串数字...保留两位
    DecimalFormat decimalFormat = new DecimalFormat("0.00");
    String priceString = decimalFormat.format(price);
    CountPriceBean countPriceBean = new CountPriceBean(priceString, count);


    //发送到主页面进行显示
    Message msg = Message.obtain();


    msg.what = 0;
    msg.obj = countPriceBean;
    handler.sendMessage(msg);
}


/**
 * 根据全选的状态更新所有商品的状态
 * @param checked
 */
public void setAllChildsChecked(boolean checked) {


    //创建一个大的结合,,,存放所有商品的数据
    List allList = new ArrayList<>();
    for (int i= 0;i listBeans = cartBean.getData().get(i).getList();
        for (int j=0;j allList, final boolean checked) {


    CartBean.DataBean.ListBean listBean = allList.get(allIndex);
    Map params = new HashMap<>();


    //?uid=71&sellerid=1&pid=1&selected=0&num=10
    params.put("uid", "98");
    params.put("sellerid", String.valueOf(listBean.getSellerid()));
    params.put("pid", String.valueOf(listBean.getPid()));


    params.put("selected", String.valueOf(checked ? 1 : 0));
    params.put("num", String.valueOf(listBean.getNum()));
    RetrofitUtil.getService().doGet(Constant.updetaUrl, params)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(ResponseBody responseBody) {
                    allIndex++;


                    if (allIndex < allList.size()) {
                        //继续更新下一条
                        updateAllChecked(allList, checked);
                    } else {
                        //重新查询
                        mainPresenter.getCartData(Constant.seleteUrl);
                    }


                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

}

}

3.)图片的加载
MyApption类

public class MyApption extends Application {
@Override
public void onCreate() {
super.onCreate();
Fresco.initialize(this);
}
}

6、布局MianAcvitity类的布局

二级列表的布局

一级列表的布局
group_layout.xml

二级列表的布局child_layout.xml

drawable包
bian_kuang.xml



check_box_selector.xml






“`

你可能感兴趣的:(学习资料学习资料)