动画跳转购物车

权限

<uses-permission android:name="android.permission.INTERNET"/>

所需要的依赖

compile 'com.squareup.okhttp3:okhttp:3.3.0'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.squareup.okio:okio:1.5.0'
compile 'com.github.bumptech.glide:glide:3.6.1'
main_activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.gjl.yuekaolianxi.view.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/back"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:background="@mipmap/ic_launcher"/>

        <TextView
            android:id="@+id/main_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="商品详情"/>
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.75dp"
        android:background="#F00"/>

    <ImageView
        android:id="@+id/main_big_pic"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher"/>

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

        <TextView
            android:id="@+id/main_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="商品名"/>

        <TextView
            android:id="@+id/main_price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="原价"/>

        <TextView
            android:id="@+id/main_price2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="折扣价"/>

    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.75dp"
        android:background="#F00"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/main_cart"
            android:layout_width="0dp"
            android:layout_height="30dp"
            android:layout_weight="1"
            android:clickable="true"
            android:gravity="center"
            android:text="购物车"/>

        <View
            android:layout_width="0.75dp"
            android:layout_height="match_parent"
            android:background="#F00"/>

        <TextView
            android:id="@+id/main_add"
            android:layout_width="0dp"
            android:layout_height="30dp"
            android:layout_weight="1"
            android:clickable="true"
            android:gravity="center"
            android:text="加入购物车"/>
    </LinearLayout>

</LinearLayout>
activity_splash

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context="com.gjl.yuekaolianxi.view.SplashActivity">


    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"/>


</LinearLayout>
activity_cart
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.gjl.yuekaolianxi.view.CartActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="购物车"
        android:textColor="@android:color/black"
        android:textSize="25sp"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.75dp"
        android:background="#999999"/>

    <ExpandableListView
        android:id="@+id/ex_list_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:groupIndicator="@null"></ExpandableListView>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.75dp"
        android:background="#999999"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="全选/反选"
            android:textColor="@android:color/black"
            android:textSize="25sp"/>

        <TextView
            android:id="@+id/cart_sum12"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="总价:0"
            android:textColor="@android:color/black"
            android:textSize="25sp"/>
    </LinearLayout>

</LinearLayout>


layout_child
<?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="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

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

    <ImageView
        android:id="@+id/child_img"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher"/>

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

        <TextView
            android:id="@+id/child_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="商品名"/>

        <TextView
            android:id="@+id/child_price"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="优惠价"
            android:textColor="@android:color/holo_red_dark"/>
    </LinearLayout>

</LinearLayout>
layout_parent
<?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="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

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

    <TextView
        android:id="@+id/parent_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="商家"
        android:textColor="@android:color/black"
        android:textSize="25sp"/>

</LinearLayout>
创建一个anim包
enter
<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:fromXDelta="100%"
    android:toXDelta="0%">

</translate>
out
<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:fromXDelta="0%"
    android:toXDelta="-100%">

</translate>
创建一个http包做网络请求
HttpConfig
public class HttpConfig {
   public static String 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
package com.gjl.yuekaolianxi.http;

import android.os.Handler;
import android.os.Message;

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

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

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public class OkHttpUtils {
   private static OkHttpUtils okHttpUtils = null;
   private MyHandler myHandler = new MyHandler();
   private OkLoadListener okLoadListener;

   //单例
   public static OkHttpUtils getInstance() {
      if (okHttpUtils == null) {
         okHttpUtils = new OkHttpUtils();
      }
      return okHttpUtils;
   }

   //get
   public void okGet(String url) {
      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();
            message.what = 0;
            message.obj = e.getMessage();
            myHandler.sendMessage(message);
         }

         @Override
         public void onResponse(Call call, Response response) throws IOException {
            Message message = myHandler.obtainMessage();
            message.what = 1;
            message.obj = response.body().string();
            myHandler.sendMessage(message);
         }
      });
   }

   //post
   public void okPost(String url, Map<String, String> map) {
      OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new MyInter()).build();
      //创建FormBody
      FormBody.Builder builder = new FormBody.Builder();
      //遍历map
      Set<String> 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();
            message.what = 0;
            message.obj = e.getMessage();
            myHandler.sendMessage(message);
         }

         @Override
         public void onResponse(Call call, Response response) throws IOException {
            Message message = myHandler.obtainMessage();
            message.what = 1;
            message.obj = response.body().string();
            myHandler.sendMessage(message);
         }
      });
   }

   //拦截器
   class MyInter implements Interceptor {
      private static final String TAG = "MyInter";
      @Override
      public Response intercept(Chain chain) throws IOException {
         //获取原来的body
         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();
            //创建新的请求
            Request newRequest = request.newBuilder().post(newBody).build();
            Response response = chain.proceed(newRequest);
            return response;
         }

         return null;
      }
   }

   //handler
   class MyHandler extends Handler {
      @Override
      public void handleMessage(Message msg) {
         switch (msg.what) {
            case 0:
               //失败
               String e = (String) msg.obj;
               okLoadListener.okLoadError(e);
               break;
            case 1:
               //成功
               String json = (String) msg.obj;
               okLoadListener.okLoadSuccess(json);
               break;
         }
      }
   }

   //提高外部调用的接口
   public void setOkLoadListener(OkLoadListener okLoadListener) {
      this.okLoadListener = okLoadListener;
   }
}
OKLoadListener
public interface OkLoadListener {
   void okLoadSuccess(String json);

   void okLoadError(String error);
}
创建一个M层model
AddListener
package com.gjl.yuekaolianxi.model;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public interface AddListener {
   void addSucess(String json);

   void addError(String error);
}
CartBean
package com.gjl.yuekaolianxi.model;

import java.util.List;

/**
 * 购物车的bean
 */

public class CartBean {
   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 {
      //添加一boolean,记录选中状态
      private boolean parentIsSelected;

      public DataBean(boolean parentIsSelected, String sellerName, String sellerid, List<ChildBean> list) {
         this.parentIsSelected = parentIsSelected;
         this.sellerName = sellerName;
         this.sellerid = sellerid;
         this.list = list;
      }

      public boolean isParentIsSelected() {
         return parentIsSelected;
      }

      public void setParentIsSelected(boolean parentIsSelected) {
         this.parentIsSelected = parentIsSelected;
      }

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

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

   public class ChildBean {

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

      public ChildBean(double bargainPrice, String createtime, String detailUrl, String images, double num, double pid, double price, double pscid, double selected, double sellerid, String subhead, String title, boolean childIsSelected) {
         this.bargainPrice = bargainPrice;
         this.createtime = createtime;
         this.detailUrl = detailUrl;
         this.images = images;
         this.num = num;
         this.pid = pid;
         this.price = price;
         this.pscid = pscid;
         this.selected = selected;
         this.sellerid = sellerid;
         this.subhead = subhead;
         this.title = title;
         this.childIsSelected = childIsSelected;
      }

      public boolean isChildIsSelected() {
         return childIsSelected;
      }

      public void setChildIsSelected(boolean childIsSelected) {
         this.childIsSelected = childIsSelected;
      }

      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 double getNum() {
         return num;
      }

      public void setNum(double num) {
         this.num = num;
      }

      public double getPid() {
         return pid;
      }

      public void setPid(double pid) {
         this.pid = pid;
      }

      public double getPrice() {
         return price;
      }

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

      public double getPscid() {
         return pscid;
      }

      public void setPscid(double pscid) {
         this.pscid = pscid;
      }

      public double getSelected() {
         return selected;
      }

      public void setSelected(double selected) {
         this.selected = selected;
      }

      public double getSellerid() {
         return sellerid;
      }

      public void setSellerid(double 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;
      }
   }
}
CartListLoadListener
package com.gjl.yuekaolianxi.model;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public interface CartListLoadListener {
   //购物车数据,加载成功
   void loadCartSuccess(String json);

   //加载失败
   void loadCartError(String error);
}
DatailBean
package com.gjl.yuekaolianxi.model;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public class DetailBean {

   /**
    * msg :
    * seller : {"description":"我是商家10","icon":"http://120.27.23.105/images/icon.png","name":"商家10","productNums":999,"score":5,"sellerid":10}
    * code : 0
    * data : {"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","itemtype":0,"pid":17,"price":299,"pscid":1,"salenum":888,"sellerid":10,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}
    */

   private String msg;
   private SellerBean seller;
   private String code;
   private DataBean data;

   public String getMsg() {
      return msg;
   }

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

   public SellerBean getSeller() {
      return seller;
   }

   public void setSeller(SellerBean seller) {
      this.seller = seller;
   }

   public String getCode() {
      return code;
   }

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

   public DataBean getData() {
      return data;
   }

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

   public static class SellerBean {
      /**
       * description : 我是商家10
       * icon : http://120.27.23.105/images/icon.png
       * name : 商家10
       * productNums : 999
       * score : 5
       * sellerid : 10
       */

      private String description;
      private String icon;
      private String name;
      private int productNums;
      private int score;
      private int sellerid;

      public String getDescription() {
         return description;
      }

      public void setDescription(String description) {
         this.description = description;
      }

      public String getIcon() {
         return icon;
      }

      public void setIcon(String icon) {
         this.icon = icon;
      }

      public String getName() {
         return name;
      }

      public void setName(String name) {
         this.name = name;
      }

      public int getProductNums() {
         return productNums;
      }

      public void setProductNums(int productNums) {
         this.productNums = productNums;
      }

      public int getScore() {
         return score;
      }

      public void setScore(int score) {
         this.score = score;
      }

      public int getSellerid() {
         return sellerid;
      }

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

   public static class DataBean {
      /**
       * 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
       * itemtype : 0
       * pid : 17
       * price : 299
       * pscid : 1
       * salenum : 888
       * sellerid : 10
       * subhead : 每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下
       * title : 北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g
       */

      private double bargainPrice;
      private String createtime;
      private String detailUrl;
      private String images;
      private double itemtype;
      private double pid;
      private double price;
      private double pscid;
      private double salenum;
      private double 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 double getItemtype() {
         return itemtype;
      }

      public void setItemtype(double itemtype) {
         this.itemtype = itemtype;
      }

      public double getPid() {
         return pid;
      }

      public void setPid(double pid) {
         this.pid = pid;
      }

      public double getPrice() {
         return price;
      }

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

      public double getPscid() {
         return pscid;
      }

      public void setPscid(double pscid) {
         this.pscid = pscid;
      }

      public double getSalenum() {
         return salenum;
      }

      public void setSalenum(double salenum) {
         this.salenum = salenum;
      }

      public double getSellerid() {
         return sellerid;
      }

      public void setSellerid(double 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;
      }
   }
}
DetailLoadLister
package com.gjl.yuekaolianxi.model;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public interface DetailLoadLister {
   void detailLoadSuccess(String json);
   void detailLoadError(String error);
}

IModel

package com.gjl.yuekaolianxi.model;

import java.util.Map;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public interface IModel {
   //请求接口,得到数据,详情页的
   void getDetailData(String url, Map<String, String> parms, DetailLoadLister detailLoadLister);

   //添加到购物车的而方法
   void addToCart(String url, Map<String, String> parms, AddListener addListener);

   //购物车页面的方法
   //显示
   void showDataToCart(String url, Map<String, String> parms, CartListLoadListener cartListLoadListener);
   //组的checkbox的点击的时候,处理选中状态
// void setParentIsChecked(boolean isChecked,);
   //全选、反选

   //计算总价
   double calcaulate(CartBean cartBean);
}
ModelImpl

package com.gjl.yuekaolianxi.model;

import android.util.Log;

import com.gjl.yuekaolianxi.http.OkHttpUtils;
import com.gjl.yuekaolianxi.http.OkLoadListener;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public class ModelImpl implements IModel {
   //加载详情页
   @Override
   public void getDetailData(String url, Map<String, String> parms, final DetailLoadLister detailLoadLister) {
      //用OkHttp请求,之后调用接口
      OkHttpUtils ok = OkHttpUtils.getInstance();
      ok.okPost(url, parms);
      ok.setOkLoadListener(new OkLoadListener() {
         @Override
         public void okLoadSuccess(String json) {
            detailLoadLister.detailLoadSuccess(json);
         }

         @Override
         public void okLoadError(String error) {
            detailLoadLister.detailLoadError(error);
         }
      });
   }


   private static final String TAG = "ModelImpl";
   //添加
   @Override
   public void addToCart(String url, Map<String, String> parms, final AddListener addListener) {
      //用OkHttp请求,之后调用接口
      OkHttpUtils ok = OkHttpUtils.getInstance();
      ok.okPost(url, parms);
      Log.d(TAG, "addToCart() returned: " + parms);
      ok.setOkLoadListener(new OkLoadListener() {
         @Override
         public void okLoadSuccess(String json) {
            addListener.addSucess(json);
         }

         @Override
         public void okLoadError(String error) {
            addListener.addError(error);
         }
      });
   }
   //购物车里面的加载数据的方法
   @Override
   public void showDataToCart(String url, Map<String, String> parms, final CartListLoadListener cartListLoadListener) {
      //开始加载
      //用OkHttp请求,之后调用接口
      OkHttpUtils ok = OkHttpUtils.getInstance();
      ok.okPost(url, parms);
      Log.d(TAG, "购物车数据---" + parms);
      ok.setOkLoadListener(new OkLoadListener() {
         @Override
         public void okLoadSuccess(String json) {
            cartListLoadListener.loadCartSuccess(json);
         }

         @Override
         public void okLoadError(String error) {
            cartListLoadListener.loadCartError(error);
         }
      });
   }
   //计算
   @Override
   public double calcaulate(CartBean cartBean) {
      double sum = 0;
      Log.d(TAG, "calcaulate() returned: " + cartBean + "===" + cartBean.getData());
      List<CartBean.DataBean> data = cartBean.getData();
      for (int i = 0; i < data.size(); i++) {
         List<CartBean.ChildBean> list = data.get(i).getList();
         for (int j = 0; j < list.size(); j++) {
            if (list.get(j).isChildIsSelected()){
               double bargainPrice = list.get(j).getBargainPrice();
               sum+=bargainPrice;
            }

         }
      }
      return sum;
   }
}
MyAdapter

package com.gjl.yuekaolianxi.model;

import android.content.Context;
import android.view.LayoutInflater;
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.gjl.yuekaolianxi.R;
import com.gjl.yuekaolianxi.presenter.PresenterImpl;
import com.gjl.yuekaolianxi.view.ICartView;

import java.util.List;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public class MyAdapter extends BaseExpandableListAdapter {
   private final Context context;
   private final CartBean cartBean;
   private final List<CartBean.DataBean> list;
   private final ICartView iCartView;

   public MyAdapter(Context context, CartBean cartBean, ICartView iCartView) {
      this.context = context;
      this.cartBean = cartBean;
      this.list = cartBean.getData();
      this.iCartView = iCartView;
   }

   //组的个数
   @Override
   public int getGroupCount() {
      return list.size();
   }

   //每个组的孩子的长度
   @Override
   public int getChildrenCount(int groupPosition) {
      return list.get(groupPosition).getList().size();
   }

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

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

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

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

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

   @Override
   public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, final ViewGroup parent) {
      ParentViewHolder parentViewHolder = null;
      if (convertView == null) {
         convertView = LayoutInflater.from(context).inflate(R.layout.layout_parent, null);
         CheckBox parent_cb = convertView.findViewById(R.id.parent_cb);
         TextView parent_tv = convertView.findViewById(R.id.parent_tv);
         parentViewHolder = new ParentViewHolder(parent_cb, parent_tv);
         convertView.setTag(parentViewHolder);
      } else {
         parentViewHolder = (ParentViewHolder) convertView.getTag();
      }
      //赋值
      parentViewHolder.getParent_cb().setChecked(list.get(groupPosition).isParentIsSelected());
      parentViewHolder.getParent_tv().setText(list.get(groupPosition).getSellerName());
      //点击事件
      parentViewHolder.getParent_cb().setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            boolean isCheked = list.get(groupPosition).isParentIsSelected();
            isCheked = !isCheked;
            list.get(groupPosition).setParentIsSelected(isCheked);
            //遍历子元素,全部置为true
            List<CartBean.ChildBean> list = MyAdapter.this.list.get(groupPosition).getList();
            for (int i = 0; i < list.size(); i++) {
               list.get(i).setChildIsSelected(isCheked);
            }
            //通知界面
            notifyDataSetChanged();
            //计算
            PresenterImpl presenter = new PresenterImpl();
            presenter.jisuan(new ModelImpl(), cartBean, iCartView);
         }
      });


      return convertView;
   }

   @Override
   public View getChildView(final int groupPosition, final int childPosition, final boolean isLastChild, View convertView, ViewGroup parent) {
      ChildeViewHolder childeViewHolder = null;
      if (convertView == null) {
         convertView = LayoutInflater.from(context).inflate(R.layout.layout_child, null);
         CheckBox child_cb = convertView.findViewById(R.id.child_cb);
         ImageView child_img = convertView.findViewById(R.id.child_img);
         TextView child_title = convertView.findViewById(R.id.child_title);
         TextView child_price = convertView.findViewById(R.id.child_price);
         childeViewHolder = new ChildeViewHolder(child_cb, child_img, child_title, child_price);
         convertView.setTag(childeViewHolder);
      } else {
         childeViewHolder = (ChildeViewHolder) convertView.getTag();
      }
      //赋值
      childeViewHolder.getChild_cb().setChecked(list.get(groupPosition).getList().get(childPosition).isChildIsSelected());
      //获取图的地址

      String images = list.get(groupPosition).getList().get(childPosition).getImages();
      String imageUrl = images.split(".jpg")[0] + ".jpg";
      Glide.with(context).load(imageUrl).into(childeViewHolder.getChild_imge());
      childeViewHolder.getChild_title().setText(list.get(groupPosition).getList().get(childPosition).getTitle());
      childeViewHolder.getChild_price().setText(list.get(groupPosition).getList().get(childPosition).getBargainPrice() + "");
      //字条目中的checkbox点击状态
      //点击事件
      childeViewHolder.getChild_cb().setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            boolean isCheked = list.get(groupPosition).getList().get(childPosition).isChildIsSelected();
            isCheked = !isCheked;
            list.get(groupPosition).getList().get(childPosition).setChildIsSelected(isCheked);
            //遍历
            List<CartBean.ChildBean> list1 = MyAdapter.this.list.get(groupPosition).getList();
            boolean flag = true;
            for (int i = 0; i < list1.size(); i++) {
               if (!list1.get(i).isChildIsSelected()) {
                  flag = false;
               }
            }
            list.get(groupPosition).setParentIsSelected(flag);
            //通知改变
            notifyDataSetChanged();
            //计算
            PresenterImpl presenter = new PresenterImpl();
            presenter.jisuan(new ModelImpl(), cartBean, iCartView);
         }
      });
      return convertView;
   }

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

   //优化
   class ParentViewHolder {
      public CheckBox parent_cb;
      public TextView parent_tv;

      public ParentViewHolder(CheckBox parent_cb, TextView parent_tv) {
         this.parent_cb = parent_cb;
         this.parent_tv = parent_tv;
      }

      public CheckBox getParent_cb() {
         return parent_cb;
      }

      public void setParent_cb(CheckBox parent_cb) {
         this.parent_cb = parent_cb;
      }

      public TextView getParent_tv() {
         return parent_tv;
      }

      public void setParent_tv(TextView parent_tv) {
         this.parent_tv = parent_tv;
      }
   }

   class ChildeViewHolder {
      public CheckBox child_cb;
      public ImageView child_imge;
      public TextView child_title;
      public TextView child_price;

      public ChildeViewHolder(CheckBox child_cb, ImageView child_imge, TextView child_title, TextView child_price) {
         this.child_cb = child_cb;
         this.child_imge = child_imge;
         this.child_title = child_title;
         this.child_price = child_price;
      }

      public CheckBox getChild_cb() {
         return child_cb;
      }

      public void setChild_cb(CheckBox child_cb) {
         this.child_cb = child_cb;
      }

      public ImageView getChild_imge() {
         return child_imge;
      }

      public void setChild_imge(ImageView child_imge) {
         this.child_imge = child_imge;
      }

      public TextView getChild_title() {
         return child_title;
      }

      public void setChild_title(TextView child_title) {
         this.child_title = child_title;
      }

      public TextView getChild_price() {
         return child_price;
      }

      public void setChild_price(TextView child_price) {
         this.child_price = child_price;
      }
   }
}
创建一个presenter

IPresenter

package com.gjl.yuekaolianxi.presenter;

import android.content.Context;

import com.gjl.yuekaolianxi.model.CartBean;
import com.gjl.yuekaolianxi.model.IModel;
import com.gjl.yuekaolianxi.view.ICartView;
import com.gjl.yuekaolianxi.view.IMainView;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public interface IPresenter {
   //将数据显示咋Detail页面
   void showDataToDetai(IModel iModel, IMainView iMainView);

   //跳转
   void jumpToCart(IMainView iMainView);

   //添加
   void addToCart(IModel iModel, IMainView iMainView);

   //购物车--
   void showDataToCart(Context context, IModel iModel, ICartView iCartView);

   void jisuan(IModel iModel, CartBean cartBean, ICartView iCartView);
}
presenterimpl

package com.gjl.yuekaolianxi.presenter;

import android.content.Context;
import android.util.Log;

import com.gjl.yuekaolianxi.http.HttpConfig;
import com.gjl.yuekaolianxi.model.AddListener;
import com.gjl.yuekaolianxi.model.CartBean;
import com.gjl.yuekaolianxi.model.CartListLoadListener;
import com.gjl.yuekaolianxi.model.DetailBean;
import com.gjl.yuekaolianxi.model.DetailLoadLister;
import com.gjl.yuekaolianxi.model.IModel;
import com.gjl.yuekaolianxi.view.ICartView;
import com.gjl.yuekaolianxi.view.IMainView;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public class PresenterImpl implements IPresenter {
   private static final String TAG = "PresenterImpl";

   //详情页显示数据的方法
   @Override
   public void showDataToDetai(IModel iModel, final IMainView iMainView) {
      Map<String, String> map = new HashMap<String, String>();
      map.put("pid", "17");
      iModel.getDetailData(HttpConfig.detail_url, map, new DetailLoadLister() {
         @Override
         public void detailLoadSuccess(String json) {
            //json---DetaiBean
            Log.d(TAG, "成---- " + json);
            Gson gson = new Gson();
            DetailBean detailBean = gson.fromJson(json, DetailBean.class);
            //传入View
            iMainView.showDetailData(detailBean);
         }

         @Override
         public void detailLoadError(String error) {
            Log.d(TAG, "detail---pres--shibai");
         }
      });
   }

   //跳转
   @Override
   public void jumpToCart(IMainView iMainView) {
      iMainView.jumpToCatActivity();
   }

   //添加
   @Override
   public void addToCart(IModel iModel, final IMainView iMainView) {
      Map<String, String> map = new HashMap<String, String>();
      map.put("pid", iMainView.getPid());
      map.put("uid", "71");
      iModel.addToCart(HttpConfig.add_url, map, new AddListener() {
         @Override
         public void addSucess(String json) {
            Log.d(TAG, "addSucess() returned: " + json);
            try {
               JSONObject object = new JSONObject(json);
               String code = object.getString("code");
               if (code.equals("0")) {
                  iMainView.showAddSucess();
               } else {
                  iMainView.shoAddError();
               }
            } catch (JSONException e) {
               e.printStackTrace();
            }

         }

         @Override
         public void addError(String error) {
            Log.d(TAG, "shibai-----");
            iMainView.shoAddError();
         }
      });
   }

   //在购物车显示数据
   @Override
   public void showDataToCart(final Context context, IModel iModel, final ICartView iCartView) {
      Map<String, String> map = new HashMap<String, String>();
      map.put("uid", "71");
      iModel.showDataToCart(HttpConfig.cartList_url, map, new CartListLoadListener() {
         @Override
         public void loadCartSuccess(String json) {
            Log.d(TAG, "购物车数据----" + json);
            //将json---Bean
            Gson gson = new Gson();
            CartBean cartBean = gson.fromJson(json, CartBean.class);
            //调用view的回调
            iCartView.showDataToCart(context, cartBean);
         }

         @Override
         public void loadCartError(String error) {

         }
      });
   }

   //计算
   @Override
   public void jisuan(IModel iModel, CartBean cartBean, ICartView iCartView) {
      Log.d(TAG, "jisuan() returned: " + iCartView.getCartBean());
      double sum = iModel.calcaulate(cartBean);
      iCartView.showSum(sum);
   }


}
v层view

AnimatourUtils

package com.gjl.yuekaolianxi.view;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.View;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public class AnimatorUtils {

   public static AnimatorSet setAnimatorSet(Context context, View view) {
      //获取屏幕一般
      DisplayMetrics metrics = context.getResources().getDisplayMetrics();
      int heightPixels = metrics.heightPixels;
      ValueAnimator tranlate = ObjectAnimator.ofFloat(view, "translationY", 0, heightPixels / 2 - view.getHeight());
      ValueAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 2.0f, 1.0f);
      ValueAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 2.0f, 1.0f);
      ValueAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 0, 1.0f);
      ValueAnimator rotation = ObjectAnimator.ofFloat(view, "rotation", 0, 360);
      //创建动画集合
      AnimatorSet set = new AnimatorSet();
      set.playTogether(tranlate, scaleX, scaleY, alpha, rotation);
      set.setDuration(3000);
      set.start();
      return set;
   }
   //动画监听

}


CartActivity

package com.gjl.yuekaolianxi.view;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.gjl.yuekaolianxi.R;
import com.gjl.yuekaolianxi.model.CartBean;
import com.gjl.yuekaolianxi.model.ModelImpl;
import com.gjl.yuekaolianxi.model.MyAdapter;
import com.gjl.yuekaolianxi.presenter.PresenterImpl;

import java.util.List;

/**
 * 商品列表页面
 */
public class CartActivity extends AppCompatActivity implements ICartView, View.OnClickListener {
   private static final String TAG = "CartActivity";
   private ExpandableListView ex_list_view;
   private CheckBox cart_cb;
   private TextView cart_sum;
   private CartBean cartBean;
   private MyAdapter myAdapter;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_cart);
      //初始化界面
      initViews();
      //调用Presenter加载数据
      PresenterImpl presenter = new PresenterImpl();
      presenter.showDataToCart(this, new ModelImpl(), this);
   }

   private void initViews() {
      ex_list_view = findViewById(R.id.ex_list_view);
      cart_cb = findViewById(R.id.cart_cb);
      cart_sum = findViewById(R.id.cart_sum12);
      //全选、反选的点击事件
      cart_cb.setOnClickListener(this);
   }

   //获取当前activity
   public Activity getActivity() {
      return this;
   }

   //展示数据的方法
   @Override
   public void showDataToCart(Context context, CartBean cartBean) {
      this.cartBean = cartBean;
      //设置适配器
      myAdapter = new MyAdapter(context, cartBean, this);
      ex_list_view.setAdapter(myAdapter);
      //将expanablelistview全部展开
      int childCount = myAdapter.getGroupCount();
      for (int i = 0; i < childCount; i++) {
         ex_list_view.expandGroup(i);
      }
   }

   //获取CartBean
   @Override
   public CartBean getCartBean() {
      return cartBean;
   }

   //显示总价的回调
   @Override
   public void showSum(double sum) {
      Log.d(TAG, "showSum() returned: " + sum + "--" + cart_sum);
      TextView tv = findViewById(R.id.cart_sum12);
      tv.setText("总价:" + sum);
   }

   //点击事件
   @Override
   public void onClick(View v) {
      switch (v.getId()) {
         case R.id.cart_cb:
            //全部置为反
            List<CartBean.DataBean> data = cartBean.getData();
            for (int i = 0; i < data.size(); i++) {
               data.get(i).setParentIsSelected(!data.get(i).isParentIsSelected());
               //子元素
               List<CartBean.ChildBean> list = data.get(i).getList();
               for (int j = 0; j < list.size(); j++) {
                  list.get(j).setChildIsSelected(!list.get(j).isChildIsSelected());
               }
            }
            //通知刷新
            myAdapter.notifyDataSetChanged();
            //计算
            PresenterImpl presenter = new PresenterImpl();
            presenter.jisuan(new ModelImpl(), cartBean, this);
            break;
      }
   }
}
ICartView

package com.gjl.yuekaolianxi.view;

import android.content.Context;

import com.gjl.yuekaolianxi.model.CartBean;

/**
 * 购物车页面
 */

public interface ICartView {
   //显示
   void showDataToCart(Context context, CartBean cartBean);
   //全选、反选

   //显示总价
   void showSum(double sum);

   CartBean getCartBean();
}
IMainView

package com.gjl.yuekaolianxi.view;

import com.gjl.yuekaolianxi.model.DetailBean;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public interface IMainView {
   void showDetailData(DetailBean detailBean);

   void jumpToCatActivity();

   void addToCart();
   //获取PID的方法
   String getPid();
   //成功的提示
   void showAddSucess();
   //失败的提示
   void shoAddError();
}
ISplashView

package com.gjl.yuekaolianxi.view;

/**
 * Created by Administrator on 2018/1/10 0010.
 */

public interface ISplashView {
   void jumpToMainActivity();
}
MainActivity

package com.gjl.yuekaolianxi.view;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gjl.yuekaolianxi.R;
import com.gjl.yuekaolianxi.model.DetailBean;
import com.gjl.yuekaolianxi.model.ModelImpl;
import com.gjl.yuekaolianxi.presenter.PresenterImpl;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, IMainView {

   private ImageView main_big_pic;
   private TextView man_name;
   private TextView main_price;
   private TextView main_price2;
   private PresenterImpl presenter;
   private DetailBean detailBean;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      //初始化界面
      initView();
      //调用Prester进行数据加载

      presenter = new PresenterImpl();
      presenter.showDataToDetai(new ModelImpl(), this);

   }

   private void initView() {
      main_big_pic = findViewById(R.id.main_big_pic);
      man_name = findViewById(R.id.main_name);
      main_price = findViewById(R.id.main_price);
      main_price2 = findViewById(R.id.main_price2);
      TextView main_cart = findViewById(R.id.main_cart);
      TextView main_add = findViewById(R.id.main_add);
      main_cart.setOnClickListener(this);
      main_add.setOnClickListener(this);
   }

   //点击事件
   @Override
   public void onClick(View v) {

      switch (v.getId()) {
         case R.id.main_cart:
            //调用跳转
            presenter.jumpToCart(this);
            break;
         case R.id.main_add:
            //添加到购物车
            Log.d("Main--", "点击---" );
            presenter.addToCart(new ModelImpl(), this);
            break;
      }
   }

   //View的方法实现
   @Override
   public void showDetailData(DetailBean detailBean) {
      this.detailBean = detailBean;
      //设置数据
      String images = detailBean.getData().getImages();
      String imgeUrl = images.split(".jpg")[0] + ".jpg";
      Glide.with(MainActivity.this).load(imgeUrl).into(main_big_pic);
      man_name.setText(detailBean.getData().getTitle());
      main_price.setText("原价:" + detailBean.getData().getPrice() + "");
      main_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
      main_price2.setText("折扣价" + detailBean.getData().getBargainPrice() + "");

   }

   @Override
   public void jumpToCatActivity() {
      //到购物车页面
      startActivity(new Intent(MainActivity.this, CartActivity.class));
      overridePendingTransition(R.anim.enter, R.anim.out);
      finish();
   }

   @Override
   public void addToCart() {

   }

   //获取pid
   @Override
   public String getPid() {
      return detailBean.getData().getPid() + "";
   }

   //成功提示
   @Override
   public void showAddSucess() {
      Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
   }

   //失败提示
   @Override
   public void shoAddError() {
      Toast.makeText(MainActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
   }
}
SplashActivity

package com.gjl.yuekaolianxi.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;

import com.gjl.yuekaolianxi.R;

/**
 * 属性动画
 * 5个
 * 跳转,监听
 */
public class SplashActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_splash);
      //初始化界面
      initViews();
   }

   private void initViews() {
      ImageView img1 = findViewById(R.id.image1);
      //创建动画
      AnimatorSet set = AnimatorUtils.setAnimatorSet(SplashActivity.this, img1);
      set.addListener(new AnimatorListenerAdapter() {
         @Override
         public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
            //加跳转动画
            overridePendingTransition(R.anim.enter, R.anim.out);
            //结束掉本页面
            finish();
         }
      });
   }

}

清单列表

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.gjl.yuekaolianxi">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".view.MainActivity">
        </activity>

            <activity android:name=".view.CartActivity">
        </activity>
        <activity android:name=".view.SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

猜你喜欢

转载自blog.csdn.net/qq_40056429/article/details/79078162