欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android购物车的实现

程序员文章站 2024-01-28 17:23:40
android购物车的实现 //配置清单文件 < uses-permission android :name = “android.permission.interne...

android购物车的实现

//配置清单文件
< uses-permission android :name = “android.permission.internet” />
--------
<activityandroid:name =“.view.mainactivity”> activity> <activityandroid:name =“.view.splashactivity”> <intent-filter> <actionandroid:name =“ android.intent.action.main“/> <categoryandroid:name =”android.intent.category.launcher“/> intent-filter> activity>
------------- ------------------------------------------
//依赖
编译'com.squareup.okhttp3:okhttp:3.3.0'
编译'com.google.code.gson:gson:2.2.4'
编译'com.squareup.okio:奥基奥:1.5.0'
编译“com.github。 bumptech.glide:滑行:3.6.1'
-------------------------------------------------- --- \
utils的层
公共类 httpconfig {
     公共静态字符串detail_url = “https://www.zhaoapi.cn/product/getproductdetail” ;
    public static string add_url = “https://www.zhaoapi.cn/product/addcart” ;
    public static string cartlist_url = “https://www.zhaoapi.cn/product/getcarts” ;
}
-------------------------------------------------- -----
公共类 okhttputils {
        私有静态 okhttputils okhttputils = null ;
          私人 myhandler myhandler = 新的 myhandler();
          私人 okloadlistener okloadlistener ;

          //单例
 public static okhttputils getinstance(){
              if(okhttputils == null){
                 okhttputils = new okhttputils();          
             }
             返回okhttputils ;
          }

          / /获取
 公共无效 okget(字符串网址){          
             okhttpclient client = new okhttpclient.builder()。addinterceptor(new myinter())。build();
             request request = new request.builder()。url(url).build();
             call call = client.newcall(request);
             call.enqueue(new callback(){
                 @
 override public void onfailure(call call,ioexception e){                
                   message message = myhandler .obtainmessage();
                   信息。什么 = 0 ;
                   信息。obj = e.getmessage();
                   myhandler .sendmessage(message);
                }

                @覆盖
 公共无效 onresponse(电话呼叫,应答响应)抛出 ioexception异常{                
                   message message = myhandler .obtainmessage();
                   信息。什么 = 1 ;
                   信息。obj = response.body()。string();
                   myhandler .sendmessage(message);
                }
             });
          }

          // post
 public void okpost(string url,map  map){          
             okhttpclient client = new okhttpclient.builder()。addinterceptor(new myinter())。build();
             //创建formbody
              formbody.builder builder = new formbody.builder();
             //遍历映射
              set  keys = map.keyset();
             for(string key:keys){
                string value = map.get(key);
                builder.add(key,value + “”);
             }
             // build
              formbody body = builder.build();
             request request = new request.builder()。url(url).post(body).build();
             call call = client.newcall(request);
             call.enqueue(new callback(){
                 @
 override public void onfailure(call call,ioexception e){                
                   message message = myhandler .obtainmessage();
                   信息。什么 = 0 ;
                   信息。obj = e.getmessage();
                   myhandler .sendmessage(message);
                }

                @覆盖
 公共无效 onresponse(电话呼叫,应答响应)抛出 ioexception异常{                
                   message message = myhandler .obtainmessage();
                   信息。什么 = 1 ;
                   信息。obj = response.body()。string();
                   myhandler .sendmessage(message);
                }
             });
          }

          //拦截器
 类 myinter 实现了 interceptor {
              private static final string tag = “myinter” ;
             @override
 public response intercept(chain chain)throws ioexception {
                 //获取原来的主体
 request request = chain.request();                                       
                requestbody body = request.body();
                if(body instanceof formbody){
                    //遍历原来的所有参数,加到新的body里面,最后将公共参数加到新的body
                    formbody.builder newbuilder = new formbody.builder();
                   for(int i = 0 ; i <((formbody)body).size(); i ++){
                      string name =((formbody)body).name(i);
                      string value =((formbody)body).value(i);

                      //放入新的
                       newbuilder.add(name,value);
                   }
                   //在将公共参数添加
                   进去newbuilder.add(“source”,“android”);
                   formbody newbody = newbuilder.build();
                   //创建新的请求
                   请求newrequest = request.newbuilder()。post(newbody).build();
                   响应响应= chain.proceed(newrequest);
                   回复回复;
                }

                返回null ;
             }
          }

          //处理程序
 类 myhandler的延伸处理程序{
              @覆盖
 公共无效的handlemessage(消息msg){
                 开关(msg。什么){
                    情况下0:
                       //失败
串e =(字符串)味精。obj ;
                      okloadlistener .okloaderror(e);
                      打破 ;
                   情况1:
                       //成功
字符串json =(字符串)味精。obj ;
                      okloadlistener                                                                   .okloadsuccess(json);
                      打破 ;
                }
             }
          }

          //提高外部调用的接口
 public void setokloadlistener(okloadlistener okloadlistener){
              this。okloadlistener = okloadlistener;          
          }
}
-------------------------------------------------- ---------
公共接口 okloadlistener {
     //网络请求成功
 void okloadsuccess(string json);
    //网络请求失败
 void okloaderror(string error);        
}


-------------------------------------------------- -----
模型层
公共接口 addcartlistener {
//添加成功
 void addcartsuccecc(string json);
//添加失败
void addcarterror(string json);
}
-------------------------------------------------- -------
公共接口 cartlistloadlistener {
     void cartloadsuccess(string json);
    void cartloaderror(string error);
}
-------------------------------------------------- ----
public interface detailloadlistener {
     void detailloadsuccess(string json);
    void detailloaderror(string json);
}
-------------------------------------------------- -----
public interface imodel {
     //详细页
 void getdetaildata(string url,map  map,detailloadlistener detailloadlistener);
    //添加购物车
 void addtocart(string url,map  map,addcartlistener addcartlistener);
    //查询数据
 void showdatatocart(string url,map  map,cartlistloadlistener cartlistloadlistener);
    //计算总价
 double countall(cartbean cartbean);                
}
* ------------------------------------------------- -----
公共类 modelimpl 实现 imodel {
     @覆盖
 公共无效 getdetaildata(字符串url,地图<字符串,字符串>地图,最终 detailloadlistener detailloadlistener){    
        okhttputils实例= okhttputils。getinstance();
        instance.okpost(url,地图);
        instance.setokloadlistener(新 okloadlistener(){
             @覆盖
 公共无效 okloadsuccess(字符串json){
                 //log.d( “请求数据”,json);
 detailloadlistener .detailloadsuccess(json);                            
            }

            @覆盖
 公共无效 okloaderror(字符串错误){
                 detailloadlistener .detailloaderror(误差);            
            }
        });

    }

    @override
 public void addtocart(string url,map  map,final addcartlistener addcartlistener){    
        okhttputils实例= okhttputils。getinstance();
        instance.okpost(url,地图);
        实例.setokloadlistener (新的 okloadlistener(){
             @
 override 公共无效 okloadsuccess(字符串json){
                 addcartlistener .addcartsuccecc(json);            
            }

            @覆盖
 公共无效 okloaderror(字符串错误){
                 addcartlistener .addcarterror(误差);            
            }
        });
    }

    @override
 public void showdatatocart(string url,map  map,final cartlistloadlistener cartlistloadlistener){    
        okhttputils实例= okhttputils。getinstance();
        instance.okpost(url,地图);
        实例.setokloadlistener (新的 okloadlistener(){
             @
 override 公共无效 okloadsuccess(字符串json){
                 cartlistloadlistener .cartloadsuccess(json);            
            }

            @覆盖
 公共无效 okloaderror(字符串错误){
                 cartlistloadlistener .cartloaderror(误差);            
            }
        });
    }

    @覆盖
 公共双 countall(cartbean cartbean){
         int num = 0 ;    
        list  data = cartbean.getdata();
        for(int i = 0 ; i  list = data.get(i).getlist();
            for(int j = 0 ; j if(list.get(j).getchildflag()){
                     double gbp = list.get(j).getprice();
                    num + = gbp;
                }
            }
        }
        返回数字;
    }
}
-------------------------------------------------- --------------------
prosenter层
公共接口iprosenter {
    //详情页
    void showdetailtodata(imodel imodel,imainview imainview);
    //添加购物车
    void addtocart(imodel imodel,imainview imainview);
    //购物车数据
    void showdatatocart(context context,imodel imodel,icartview icartview);
    void countall(imodel imodel,icartview icartview,cartbean cartbean);
}
-------------------------------------------------- --------------------



public class presenterimpl implements iprosenter {
     private static final string tag = “presenterimpl” ;
    @override
 public void showdetailtodata(imodel imodel,final imainview imainview){
        // log.d(“请求数据”,“走没走”);
map  map = new hashmap ();            
        map.put(“pid”,“71”);
        imodel.getdetaildata(httpconfig。detail_url,地图,新 detailloadlistener(){
             @覆盖
 公共无效 detailloadsuccess(json字符串){            
                日志。d(“请求数据----”,json);
                gson gson = new gson();
                detailbean豆= gson.fromjson(json,detailbean。类);
                imainview .showdetaildata(bean);
            }
            @覆盖
 公共无效 detailloaderror(字符串json){            
                日志。d(tag,“失败”);
            }
        });
    }

    @override
 public void addtocart(imodel imodel,final imainview imainview){    
        map  map = new hashmap ();
        map.put(“pid”,imainview.getpid());
        map.put(“uid”,“71”);
        imodel.addtocart(httpconfig。add_url,地图,新 addcartlistener(){
             @覆盖
 公共无效 addcartsuccecc(json字符串){
                 尝试 {            
                    jsonobject obj = new jsonobject(json);
                    string code = obj.getstring(“code”);
                    if(code.equals(“0”)){
                         imainview .showaddsuccsee(json);
                        日志。d(tag,“添加数据成功”);
                    } 其他 {
                         imainview .showadderror(json);
                        日志。d(tag,“添加数据失败”);
                    }
                } 捕获(jsonexception e){
                    e.printstacktrace();
                }
            }
            @覆盖
 公共无效 addcarterror(字符串json){
                 imainview .showadderror(json);            
            }
        });
    }

    @override
 public void showdatatocart(final context context,imodel imodel,final icartview icartview){    
        map  map = new hashmap ();
        map.put(“uid”,“71”);
        imodel.showdatatocart(httpconfig。cartlist_url,地图,新 cartlistloadlistener(){
             @覆盖
 公共无效 cartloadsuccess(json字符串){            
                gson gson = new gson();
                cartbean购物= gson.fromjson(json,cartbean。类);
                日志。d(“显示数据”,cart.tostring());
                icartview .showdatatocart(context,cart);
            }

            @覆盖
 公共无效 cartloaderror(字符串错误){            

            }
        });
    }

    @覆盖
 公共无效 countall(imodel imodel,icartview icartview,cartbean cartbean){
         双所有= imodel.countall(cartbean);    
        日志。d(“总价格”,all + “”);
            icartview.shownum(全部);
    }

}
-------------------------------------------------- --------------------------------
//查看层
public class animatorutils {
     public static animatorset setanimatorset(context context,view view){
         //获取屏幕宽度的一半属性动画
 int pixels = context.getresources()。getdisplaymetrics()。高度像素 ;        
        objectanimator翻译y = objectanimator。offloat(view,“translationy”,0,pixels / 2);
        objectanimator scalex = objectanimator。offloat(view,“scalex”,2.0f,1.0f);
        objectanimator scaley = objectanimator。offloat(view,“scaley”,2.0f,1.0f);
        objectanimator alpha = objectanimator。offloat(视图,“阿尔法”,0,1.0f);
        objectanimator旋转= objectanimator。offloat(视图,“旋转”,0,360);
        animatorset set = new animatorset();
        set.playtogether(translationy,将scalex,的scaley,α,旋转);
        set.setduration(3000);
        set.start();
        回报集;
    }
}
-------------------------------------------------- -----------------------------------------
公共类 splashactivity 扩展 appcompatactivity {

    私人 imageview img ;

    @override
 保护无效的 oncreate(bundle savedinstancestate){
         超级 .oncreate(savedinstancestate);    
        的setcontentview(r.layout activity_splash);
        initviews();

    }
    private void initviews(){
         img =(imageview)findviewbyid(r.id。splash_img);
        animatorset set = animatorutils。setanimatorset(splashactivity。此,img);
        set.addlistener(new animatorlisteneradapter(){
             @
 override public void onanimationend(animator animation){
                 super .onanimationend(animation);            
            startactivity(新的意向书(splashactivity。这,mainactivity。类));
            //加跳转动画
                 overridependingtransition(r.anim。输入,r.anim。出来);
                //结束本页面
                光洁度();
            }
        });
    }
}
-------------------------------------------------- --------------------------------------------
公共接口 icartview {
     void showdatatocart(context context,cartbean cartbean);
    void shownum(double num);
    cartbean getcartbean();
}

-------------------------------------------------- -----------------------------------------
公共类 cartactivity 扩展 appcompatactivity 实现 icartview {

    private expandablelistview exp ;
    私人 checkbox 框 ;
    私人 textview priceall ;
    私人 cartbean cartbean ;
    私人 myadapter myadapter ;

    @override
 保护无效的 oncreate(bundle savedinstancestate){
         超级 .oncreate(savedinstancestate);    
        的setcontentview(r.layout activity_cart);
        initviews();
        presenterimpl presenter = new presenterimpl();
        presenter.showdatatocart(this,new modelimpl(),this);
    }

    private void initviews(){
         exp =(expandablelistview)findviewbyid(r.id。cart_exp);
        box =(checkbox)findviewbyid(r.id。cart_box);
        priceall =(textview)findviewbyid(r.id。cart_priceall);
        box .setonclicklistener(new view.onclicklistener(){ @
 override
             public void onclick(view v){            
                list  data = cartbean .getdata();
                for(int i = 0 ; i  list = data.get(i).getlist();
                    for(int j = 0 ; j myadapter .notifydatasetchanged();
                presenterimpl presenter = new presenterimpl();
                presenter.countall(新 modelimpl(),cartactivity。这,cartbean);
            }
        });
    }
        //显示数据
 @override
 public void showdatatocart(context context,cartbean cartbean){
         this。cartbean = cartbean;
        myadapter = new myadapter(context,cartbean,this);
        exp .setadapter(myadapter);
        //展开所有的列表
 int childcount = myadapter .getgroupcount();
        for(int i = 0 ; i exp .expandgroup(i);               
        }
    }

    @覆盖
 公共无效 shownum(双 num){
         priceall .settext( “ 总价:” + num);    
    }

    @覆盖
 公共 cartbean getcartbean(){
         返回cartbean ;    
    }
}
-------------------------------------------------- ----------------------------
公共接口 imainview {
     无效 showdetaildata(detailbean豆);
    void addtocart();
    string getpid();
    void showaddsuccsee(string json);
    void showadderror(string error);
}
-------------------------------------------------- ------
公共类 mainactivity 扩展 appcompatactivity 实现 imainview {

    私人 imageview img ;
    私人 textview 名称 ;
    私人 textview 价格 ;
    私人 textview price_to ;
    私人 textview 添加 ;
    私人 textview 购物车 ;
    私人 presenterimpl presenter ;
    私人 detailbean 豆 ;

    @override
 保护无效的 oncreate(bundle savedinstancestate){
         超级 .oncreate(savedinstancestate);    
        的setcontentview(r.layout activity_main);
        initview();
        presenter = new presenterimpl();
        presenter .showdetailtodata(new modelimpl(),this);
    }

    private void initview(){
         img =(imageview)findviewbyid(r.id。main_img);
        name =(textview)findviewbyid(r.id。main_name);
        price =(textview)findviewbyid(r.id。main_price);
        price_to =(textview)findviewbyid(r.id。main_priceto);
        add =(textview)findviewbyid(r.id.main_add);
        cart =(textview)findviewbyid(r.id.main_cart);
        cart .setonclicklistener(new view.onclicklistener(){ @
 override
                        public void onclick(view v){
                startactivity(新的意向书(mainactivity。这,cartactivity。类));
                overridependingtransition(r.anim 输入,r.anim。出来);
                完();
            }
        });
        添加 .setonclicklistener(新 view.onclicklistener(){
             @覆盖
 公共无效的onclick(视图v){
                 主持人 .addtocart(新 modelimpl(),mainactivity。此);            
            }
        });
    }

    private static final string tag = “mainactivity” ;
    @override
 public void showdetaildata(detailbean bean){
         this。bean = bean;    
        日志。d(tag,“--- shuju ====” + bean);
        string images = bean.getdata()。getimages();
        string image = images.split(“.jpg”)[ 0 ] + “.jpg” ;
        滑行。与(mainactivity。此).load(图像).into(img);
        name .settext(bean.getdata()。gettitle());
        price .settext(“原价:” + bean.getdata()。getprice());
        price_to .settext(“折扣价” + bean.getdata()。getbargainprice());
    }

    @override
 public void addtocart(){    

    }

    @override
 public string getpid(){
         return bean .getdata()。getpid()+ “” ;    
    }

    @覆盖
 公共无效 showaddsuccsee(字符串json){    

    }

    @覆盖
 公共无效 showadderror(字符串错误){    

    }
}
-------------------------------------------------- ------------------
公共类 myadapter 扩展 baseexpandablelistadapter {
     private final上下文上下文 ;
    私人终极 cartbean cartbean ;
    私人最终 icartview icartview ;
    私人最终列表 列表 ;
    私人 groupviewholder 持有人 ;
    私人 childviewholder holder1 ;

    公共 myadapter(上下文上下文,cartbean cartbean,icartview icartview){
     this。context = context;
    这个。cartbean = cartbean;
    这个。icartview = icartview;
    这个。list = cartbean.getdata();
    }

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

    @覆盖
 公共布尔 hasstableids(){
         返回false ;    
    }

    @override
 public view getgroupview(final int groupposition,boolean isexpanded,view convertview,viewgroup parent){
         if(convertview == null){    
            convertview = view。膨胀(上下文。,r.layout groupitem,空);
            checkbox group_box = convertview.findviewbyid(r.id。group_box);
            textview的组名= convertview.findviewbyid(r.id group_name);
            holder = new groupviewholder(group_box,group_name);
            convertview.settag(持有者);
        } else {
              holder =(groupviewholder)convertview.gettag();
        }
        持有者 .getgroup_box()。setchecked(list .get(groupposition).getgroupflag());
        持有者 .getgroup_name()。settext(list .get(groupposition).getsellername());
        保持器。.getgroup_box()setonclicklistener(新 view.onclicklistener(){
             @覆盖
 公共无效的onclick(视图v){
                 布尔 iscleked = 列表获得(groupposition).getgroupflag();            
                iscleked = iscleked!;
                list .get(groupposition).setgroupflag(iscleked);
                list  beans = myadapter。这个。list .get(groupposition).getlist();
                for(int i = 0 ; i new presenterimpl();
                presenter.countall(new modelimpl(),icartview,cartbean);
            }
        });
        返回 convertview;
    }

    @override
 public view getchildview(final int groupposition,final int childposition,boolean islastchild,view convertview,viewgroup parent){
        if(convertview == null){    
           convertview = view。膨胀(上下文。,r.layout childitem,空);
           checkbox child_box = convertview.findviewbyid(r.id。child_box);
           imageview child_img = convertview.findviewbyid(r.id。child_img);
           textview child_subhead = convertview.findviewbyid(r.id。child_subhead);
           textview child_price = convertview.findviewbyid(r.id。child_price);
           holder1 = 新的 childviewholder(child_box,child_img,child_subhead,child_price);
           convertview.settag(holder1);
       } else {
             holder1 =(childviewholder)convertview.gettag();
       }
       holder1 .getchild_box()。setchecked(list .get(groupposition).getlist()。get(childposition).getchildflag());
        string images = list .get(groupposition).getlist()。get(childposition).getimages();
        string image = images.split(“.jpg”)[ 0 ] + “.jpg” ;
        日志。d(“图片”,图片);
        滑行。与(上下文).load(图像).into(holder1 .getchild_img());
       holder1 .getchild_subhead()。settext(list .get(groupposition).getlist()。get(childposition).getsubhead());
       holder1 .getchild_price()。settext(list .get(groupposition).getlist()。get(childposition).getprice()+ “”);

        holder1 .getchild_box()。setonclicklistener(new view.onclicklistener(){ @
 override
             public void onclick(view v){
                 boolean iscleked = list .get(groupposition).getlist()。get(childposition).getchildflag();            
                iscleked = iscleked!;
                list .get(groupposition).getlist()。get(childposition).setchildflag(iscleked);
                list  beans = myadapter。这个。list .get(groupposition).getlist();
                布尔标志= 真 ;
                for(int i = 0 ; i if(!beans.get(i).getchildflag()){
                        flag = false ;
                    }
                }
                list .get(groupposition).setgroupflag(flag);
                notifydatasetchanged();
                presenterimpl presenter = new presenterimpl();
                presenter.countall(new modelimpl(),icartview,cartbean);
            }
        });
        返回 convertview;
    }

    @覆盖
 公共布尔 ischildselectable(int groupposition,int childposition){
         返回false ;    
    }
    class groupviewholder {
         private checkbox group_box ;
        私人 textview 组名 ;

        public groupviewholder(checkbox group_box,textview group_name){
             this。group_box = group_box;
            这个。group_name = group_name;
        }

        public checkbox getgroup_box(){
             return group_box ;
        }

        public void setgroup_box(checkbox group_box){
             this。group_box = group_box;
        }

        public textview getgroup_name(){
             return group_name ;
        }

        public void setgroup_name(textview group_name){
             this。group_name = group_name;
        }
    }
    class childviewholder {
        private checkbox child_box ;
        私人 imageview child_img ;
        私人 textview的child_subhead ;
        私人 textview的child_price ;

        public childviewholder(checkbox child_box,imageview child_img,textview child_subhead,textview child_price){
             this。child_box = child_box;
            这个。child_img = child_img;
            这个。child_subhead = child_subhead;
            这个。child_price = child_price;
        }

        public checkbox getchild_box(){
             return child_box ;
        }

        public void setchild_box(checkbox child_box){
             this。child_box = child_box;
        }

        public imageview getchild_img(){
             return child_img ;
        }

        public void setchild_img(imageview child_img){
             this。child_img = child_img;
        }

        public textview getchild_subhead(){
             return child_subhead ;
        }

        public void setchild_subhead(textview child_subhead){
             this。child_subhead = child_subhead;
        }

        public textview getchild_price(){
             return child_price ;
        }

        public void setchild_price(textview child_price){
             this。child_price = child_price;
        }
    }
}