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

Android实现购物车整体页面逻辑详解

程序员文章站 2023-11-14 14:30:28
本文为大家讲解了android实现购物车的整体页面逻辑,供大家参考,具体内容如下 mainactivity.java public class mainac...

本文为大家讲解了android实现购物车的整体页面逻辑,供大家参考,具体内容如下

mainactivity.java

public class mainactivity extends appcompatactivity implements view.onclicklistener{

  string url = "http://www.zhaoapi.cn/product/getcarts";
  private expandablelistview el_cart;
  private checkbox cb_cart_all_select;
  private textview tv_cart_total_price;
  private button btn_cart_pay;
  myadapter adapter;
  @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");
    okhtttputils.getinstance().dopost(url, map, new okhtttputils.okcallback() {
      @override
      public void onfailure(exception e) {

      }

      @override
      public void onresponse(string json) {

        cartinfo cartinfo = new gson().fromjson(json, cartinfo.class);
        if ("0".equals(cartinfo.getcode())){
          list<cartinfo.databean> data = cartinfo.getdata();
          adapter = new myadapter(data);
          el_cart.setadapter(adapter);

          //展开二级列表
          for(int x=0; x<data.size(); x++){
            el_cart.expandgroup(x);
          }

          adapter.setoncartlistchangelistener(new myadapter.oncartlistchangelistener() {
            @override
            public void onsellercheckedchange(int i) {

              //商家被点击
              boolean currentsellerallproductselected = adapter.iscurrentsellerallproductselected(i);
              adapter.changecurrentsellerallproductsstatus(i, !currentsellerallproductselected);
              adapter.notifydatasetchanged();
              //b.刷新底部数据
              refreshselectedandtotalpriceandtotalnumber();
            }

            @override
            public void onproductcheckedchange(int i, int i1) {

              //点击商品得checkbox
              adapter.changecurrentproductstatus(i,i1);
              adapter.notifydatasetchanged();
              //b.刷新底部数据
              refreshselectedandtotalpriceandtotalnumber();
            }

            @override
            public void onproducnumberchange(int i, int i1, int number) {

              //当加减被点击
              adapter.changecurrentproductnumber(i,i1,number);
              adapter.notifydatasetchanged();
              //b.刷新底部数据
              refreshselectedandtotalpriceandtotalnumber();
            }
          });
        }
      }
    });
  }

  //b.刷新checkbox状态和总价和总数量
  private void refreshselectedandtotalpriceandtotalnumber() {
    //去判断是否所有得商品都被选中
    boolean allproductsselected = adapter.isallproductsselected();
    //设置给全选checkbox
    cb_cart_all_select.setchecked(allproductsselected);

    //计算总价
    float totalprice = adapter.calculatetotalprice();
    tv_cart_total_price.settext("总价 " + totalprice);

    //计算总数量
    int totalnumber = adapter.calculatetotalnumber();
    btn_cart_pay.settext("去结算(" + totalnumber + ")");
  }

  //初始化的操作
  private void initview() {
    el_cart = (expandablelistview) findviewbyid(r.id.el_cart);
    cb_cart_all_select = (checkbox) findviewbyid(r.id.cb_cart_all_select);
    tv_cart_total_price = (textview) findviewbyid(r.id.tv_cart_total_price);
    btn_cart_pay = (button) findviewbyid(r.id.btn_cart_pay);

    cb_cart_all_select.setonclicklistener(this);
  }

  @override
  public void onclick(view view) {

    switch (view.getid()){
      case r.id.cb_cart_all_select:

        //底部全选按钮
        //时候所有得商品都被选中
        boolean allproductsselected = adapter.isallproductsselected();
        adapter.changeallproductstatus(!allproductsselected);
        adapter.notifydatasetchanged();
        //刷新底部数据
        refreshselectedandtotalpriceandtotalnumber();
        break;
    }
  }
}

myadapter.java

public class myadapter extends baseexpandablelistadapter{

  private list<cartinfo.databean> list;
  public myadapter(list<cartinfo.databean> data) {
    list=data;
  }

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

  @override
  public int getchildrencount(int i) {
    return list.get(i).getlist()==null ? 0 :list.get(i).getlist().size();
  }

  @override
  public view getgroupview(final int i, boolean b, view view, viewgroup viewgroup) {

    //先拿到bean里组的数据,看hijson
    cartinfo.databean databean = list.get(i);
    parentviewholder parentviewholder;
    if (view == null) {
      view = view.inflate(viewgroup.getcontext(), r.layout.item_cart_parent, null);
      parentviewholder = new parentviewholder(view);
      view.settag(parentviewholder);
    } else {
      parentviewholder = (parentviewholder) view.gettag();
    }
    parentviewholder.seller_name_tv.settext(databean.getsellername());

    boolean currentsellerallproductselected = iscurrentsellerallproductselected(i);
    parentviewholder.seller_cb.setchecked(currentsellerallproductselected);

    //d.设置点击checkbox
    parentviewholder.seller_cb.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        if (moncartlistchangelistener !=null){
          moncartlistchangelistener.onsellercheckedchange(i);
        }
      }
    });
    return view;
  }


  @override
  public view getchildview(final int i, final int i1, boolean b, view view, viewgroup viewgroup) {

    cartinfo.databean databean = list.get(i);
    list<cartinfo.databean.listbean> list1 = databean.getlist();
    cartinfo.databean.listbean listbean = list1.get(i1);
    childviewholder childviewholder;


    if (view == null) {
      view = view.inflate(viewgroup.getcontext(), r.layout.item_cart_child, null);
      childviewholder = new childviewholder(view);
      view.settag(childviewholder);
    } else {
      childviewholder=(childviewholder)view.gettag();
    }
    //设置商品名字
    childviewholder.product_title_name_tv.settext(listbean.gettitle());
    //设置商品单价
    childviewholder.product_price_tv.settext(listbean.getprice()+"");
    //设置复选框是否选中
    childviewholder.child_cb.setchecked(listbean.getselected() == 1);

    //设置组合式自定义控件内部的数量
    childviewholder.add_remove_view.setnumber(listbean.getnum());

    //d.设置商品checkbox的点击事件,通过接口回调,暴露给外面
    childviewholder.child_cb.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        if (moncartlistchangelistener != null){
          moncartlistchangelistener.onproductcheckedchange(i,i1);
        }
      }
    });

    //d.设置商品数量的点击事件,通过接口回调,暴露给外面
    childviewholder.add_remove_view.setonnumberchangelistener(new addsubview.onnumberchangelistener() {
      @override
      public void onnumberchange(int num) {
        if (moncartlistchangelistener !=null){
          moncartlistchangelistener.onproducnumberchange(i,i1,num);
        }
      }
    });
    return view;
  }

  public boolean iscurrentsellerallproductselected(int i){//根据商品改变商家--如果商品全部选中商家则选中--有一个商品没选中则商家不选中
    cartinfo.databean databean = list.get(i);
    list<cartinfo.databean.listbean> beans = databean.getlist();
    for (cartinfo.databean.listbean bean : beans){

      if (bean.getselected()==0){
        return false;
      }

    }
        return true;
  }

  public boolean isallproductsselected(){ //根据商品改变全选--如果商品全部选中全选则选中--有一个商品没选中则全选不选中
    for (int x=0;x<list.size();x++){
      cartinfo.databean databean = list.get(x);
      list<cartinfo.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 calculatetotalnumber(){ //计算总数量
    int totalnumber=0;
    for (int i=0;i<list.size();i++){
      cartinfo.databean databean = list.get(i);
      list<cartinfo.databean.listbean> list1 = databean.getlist();
      for (int j=0;j<list1.size();j++){
        if (list1.get(j).getselected()==1){
          int num = list1.get(j).getnum();

          totalnumber+=num;
        }
      }
    }

    return totalnumber;
  }


  public float calculatetotalprice(){ //获取总价
    float totalprice=0;
    for (int i=0;i<list.size();i++){
      cartinfo.databean databean = list.get(i);
      list<cartinfo.databean.listbean> list = databean.getlist();
      for (int j=0;j<list.size();j++){
        if (list.get(j).getselected()==1){
          float price = list.get(j).getprice();
          int num = list.get(j).getnum();
          totalprice+=price*num;
        }
      }
    }
    return totalprice;
  }
  //c.当商品组的全选框点击时,更新所有商品的状态
  public void changecurrentsellerallproductsstatus(int i,boolean isselected){

    cartinfo.databean databean = list.get(i);
    list<cartinfo.databean.listbean> beans = databean.getlist();
    for (int j=0;j<beans.size();j++){
      cartinfo.databean.listbean bean = beans.get(j);
      bean.setselected(isselected ?1 :0);
    }
  }

  //c.当商家子条目的全选框选中时,更新其状态
  public void changecurrentproductstatus(int i , int i1){
    cartinfo.databean databean = list.get(i);
    list<cartinfo.databean.listbean> list = databean.getlist();
    cartinfo.databean.listbean listbean = list.get(i1);
    listbean.setselected(listbean.getselected() == 0 ? 1 : 0 );

  }
  //c.设置所有商品的状态
  public void changeallproductstatus(boolean selected){
    for(int x=0; x<list.size() ; x++){
      cartinfo.databean databean = list.get(x);
      list<cartinfo.databean.listbean> list = databean.getlist();
      for(int j=0; j<list.size(); j++){
        list.get(j).setselected(selected ? 1 : 0);
      }
    }
  }

  //c.当加减器被点击时,调用,改变里面当前商品的数量 参数1定位那个商家  参数2定位哪个商品 参数3定位改变具体的数量是多少
  public void changecurrentproductnumber(int i,int i1,int number){
    cartinfo.databean databean = list.get(i);
    list<cartinfo.databean.listbean> list = databean.getlist();
    cartinfo.databean.listbean listbean = list.get(i1);
    listbean.setnum(number);
  }

  public interface oncartlistchangelistener{
    /**
     * 当商家的checkbox点击时回调
     */
    void onsellercheckedchange(int i);

    /**
     * 当点击子条目商品的checkbox回调
     */
    void onproductcheckedchange(int i ,int i1);

    /**
     * 当点击加减按钮的回调
     */
    void onproducnumberchange(int i , int i1 , int number);

  }
  //d.
  oncartlistchangelistener moncartlistchangelistener;
  //d.
  public void setoncartlistchangelistener(oncartlistchangelistener oncartlistchangelistener){
    moncartlistchangelistener = oncartlistchangelistener ;
  }

  public static class parentviewholder {
    public checkbox seller_cb;
    public textview seller_name_tv;

    public parentviewholder(view rootview) {
      this.seller_cb = (checkbox) rootview.findviewbyid(r.id.seller_cb);
      this.seller_name_tv = (textview) rootview.findviewbyid(r.id.seller_name_tv);
    }
  }

  public static class childviewholder {
    public checkbox child_cb;
    public imageview product_icon_iv;
    public textview product_title_name_tv;
    public textview product_price_tv;
    public addsubview 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 = (addsubview) rootview.findviewbyid(r.id.add_remove_view);
    }
  }

  @override
  public object getgroup(int i) {
    return null;
  }

  @override
  public object getchild(int i, int i1) {
    return null;
  }

  @override
  public long getgroupid(int i) {
    return 0;
  }

  @override
  public long getchildid(int i, int i1) {
    return 0;
  }

  @override
  public boolean hasstableids() {
    return false;
  }


  @override
  public boolean ischildselectable(int i, int i1) {
    return false;
  }
}

activity_main.xml

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <expandablelistview
    android:id="@+id/el_cart"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginbottom="60dp" />

  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_alignparentbottom="true"
    android:background="#eeeeee"
    android:gravity="center_vertical">

    <checkbox
      android:id="@+id/cb_cart_all_select"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />

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

    <textview
      android:id="@+id/tv_cart_total_price"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:paddingleft="20dp"
      android:text="合计:¥0.00" />

    <button
      android:id="@+id/btn_cart_pay"
      android:layout_width="100dp"
      android:layout_height="match_parent"
      android:text="去结算(0)" />
  </linearlayout>

</relativelayout>

addsubview.java

public class addsubview extends linearlayout implements view.onclicklistener{  //组合式控件
  private int number = 1;
  private textview sub_tv;
  private textview product_number_tv;
  private textview add_tv;

  public addsubview(context context) {
    this(context,null);
  }

  public addsubview(context context, @nullable attributeset attrs) {
    this(context, attrs,0);
  }

  public addsubview(context context, @nullable attributeset attrs, int defstyleattr) {
    super(context, attrs, defstyleattr);

    view view = inflate(context, r.layout.add_remove, 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 view) {
    switch (view.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:

        if (number<8){
          ++number;
          product_number_tv.settext(number+"");
          if (onnumberchangelistener!=null){
            onnumberchangelistener.onnumberchange(number);
          }
        }else {
          toast.maketext(getcontext(), "不能再多了", toast.length_short).show();
        }
        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;
  }

  interface onnumberchangelistener {
    void onnumberchange(int num);
  }
}

add_remove.xml

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

item_cart_parent.xml

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"   //商家条目
  android:layout_width="match_parent"
  android:layout_height="60dp"
  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>

item_cart_child.xml

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="120dp"
  android:gravity="center_vertical">

  <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="80dp"
    android:layout_height="80dp"
    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>

  <fanruiqi.bwie.com.shopcat.addsubview
    android:id="@+id/add_remove_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginright="10dp" />
</linearlayout>

okhttputils.java

public class okhtttputils {
  private static okhtttputils mokhtttputils;
  private okhttpclient mokhttpclien;
  private final handler mhandler;

  private okhtttputils() {

    //创建一个主线程的handler
    mhandler = new handler(looper.getmainlooper());
    mokhttpclien = new okhttpclient.builder()
        .connecttimeout(5000, timeunit.milliseconds)
        .readtimeout(5000, timeunit.milliseconds)
        .writetimeout(5000, timeunit.milliseconds)
        .build();
  }

  //单例模式
  public static okhtttputils getinstance() {
    if (mokhtttputils == null) {
      synchronized (okhtttputils.class) {
        if (mokhtttputils == null) {
          return mokhtttputils = new okhtttputils();
        }
      }
    }
    return mokhtttputils;
  }

  public interface okcallback {
    void onfailure(exception e);
    void onresponse(string json);
  }


  public void dopost(string url, map<string, string> map, final okcallback okcallback) {
    //创建formbody的对象,把表单添加到formbody中
    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 request = new request.builder()
        .post(formbody)
        .url(url)
        .build();
    //创建call对象
    final call call = mokhttpclien.newcall(request);
    call.enqueue(new callback() {
      @override
      public void onfailure(call call, final ioexception e) {
        if (okcallback != null) {
          //切换到主线程
          mhandler.post(new runnable() {
            @override
            public void run() {
              okcallback.onfailure(e);
            }
          });
        }
      }
      @override
      public void onresponse(call call, final response response) throws ioexception {
        try {
          if (response != null && response.issuccessful()) {
            final string json = response.body().string();
            mhandler.post(new runnable() {
              @override
              public void run() {
                if (okcallback != null) {
                  okcallback.onresponse(json);
                  return;
                }
              }
            });
          }
        } catch (ioexception e) {
          e.printstacktrace();
        }
        if (okcallback != null) {
          okcallback.onfailure(new exception("网络异常"));
        }
      }
    });
  }




  //封装doget的网络请求
  public void doget(string url, final okcallback okcallback) {
    request request = new request.builder()
        .get()
        .url(url)
        .build();

    final call call = mokhttpclien.newcall(request);
    call.enqueue(new callback() {
      @override
      public void onfailure(call call, final ioexception e) {
        if (okcallback != null) {
          //切换到主线程
          mhandler.post(new runnable() {
            @override
            public void run() {
              okcallback.onfailure(e);
            }
          });
        }
      }

      @override
      public void onresponse(call call, final response response) throws ioexception {

        try {
          if (response != null && response.issuccessful()) {
            final string json = response.body().string();
            mhandler.post(new runnable() {
              @override
              public void run() {
                if (okcallback != null) {
                  okcallback.onresponse(json);
                  return;
                }

              }
            });
          }
        } catch (ioexception e) {
          e.printstacktrace();
        }

      }
    });
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。