一些依赖
compile 'com.squareup.okhttp3:okhttp:3.6.0' compile 'com.squareup.okio:okio:1.11.0' compile 'com.google.code.gson:gson:2.8.2' compile 'com.android.support:recyclerview-v7:25.0.1' compile 'com.github.bumptech.glide:glide:3.7.0' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' 清单文件drawable 目录下<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />android:name=".application.DashApplication"
bian_kuang_line.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#ffffff" /> <stroke android:width="0.1dp" android:color="#000000" /> </shape>check_box_selector.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:drawable="@drawable/shopping_cart_checked"/> <item android:state_checked="false" android:drawable="@drawable/shopping_cart_none_check"/> <item android:drawable="@drawable/shopping_cart_none_check"/> </selector>drawable-xhdpi
两张图片
布局文件
activity_main.xml
<?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" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> </LinearLayout>cart_activity_layout.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ScrollView android:layout_above="@+id/linear_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <!--购物车的二级列表--> <com.example.gouwuche.view.custom.CartExpanableListview android:id="@+id/expanable_listview" android:layout_width="match_parent" android:layout_height="wrap_content"> </com.example.gouwuche.view.custom.CartExpanableListview> <!--为你推荐--> <LinearLayout android:layout_marginTop="20dp" android:orientation="vertical" android:background="#00ff00" android:layout_width="match_parent" android:layout_height="500dp"> </LinearLayout> </LinearLayout> </ScrollView> <RelativeLayout android:visibility="gone" android:id="@+id/relative_progress" android:layout_above="@+id/linear_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <ProgressBar android:layout_centerInParent="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> <LinearLayout android:id="@+id/linear_layout" android:layout_alignParentBottom="true" android:gravity="center_vertical" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="50dp"> <CheckBox android:layout_marginLeft="10dp" android:button="@null" android:background="@drawable/check_box_selector" android:id="@+id/check_all" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_total" android:text="合计:¥0.00" android:layout_weight="2" android:layout_width="0dp" android:layout_height="wrap_content" /> <TextView android:text="去结算(0)" android:background="#ff0000" android:textColor="#ffffff" android:gravity="center" android:id="@+id/text_buy" android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" /> </LinearLayout> </RelativeLayout>child_item_layout.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:padding="10dp" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:id="@+id/rel" android:layout_toLeftOf="@+id/text_delete" android:layout_width="match_parent" android:layout_height="match_parent"> <CheckBox android:layout_centerVertical="true" android:id="@+id/check_child" android:button="@null" android:background="@drawable/check_box_selector" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/image_good" android:layout_centerVertical="true" android:layout_toRightOf="@+id/check_child" android:layout_marginLeft="10dp" android:layout_width="80dp" android:layout_height="80dp" /> <TextView android:id="@+id/text_title" android:layout_toRightOf="@+id/image_good" android:layout_marginLeft="10dp" android:layout_alignTop="@+id/image_good" android:maxLines="2" android:minLines="2" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_price" android:layout_toRightOf="@+id/image_good" android:layout_marginLeft="10dp" android:layout_alignBottom="@+id/image_good" android:text="¥99.99" android:textColor="#ff0000" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:layout_alignParentRight="true" android:layout_alignBottom="@+id/image_good" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/text_jian" android:text="一" android:padding="5dp" android:background="@drawable/bian_kuang_line" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:gravity="center" android:id="@+id/text_num" android:paddingLeft="10dp" android:paddingRight="10dp" android:background="@drawable/bian_kuang_line" android:layout_width="wrap_content" android:layout_height="match_parent" /> <TextView android:id="@+id/text_add" android:text="十" android:padding="5dp" android:background="@drawable/bian_kuang_line" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </RelativeLayout> <TextView android:layout_marginLeft="3dp" android:layout_alignParentRight="true" android:layout_alignTop="@+id/rel" android:layout_alignBottom="@+id/rel" android:id="@+id/text_delete" android:background="#ff0000" android:text="删除" android:gravity="center" android:textColor="#ffffff" android:layout_width="50dp" android:layout_height="match_parent" /> </RelativeLayout>group_item_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:gravity="center_vertical" android:padding="10dp" android:layout_width="match_parent" android:layout_height="match_parent"> <CheckBox android:button="@null" android:background="@drawable/check_box_selector" android:id="@+id/check_group" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_marginLeft="10dp" android:text="京东自营" android:id="@+id/text_group" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>Mainactivity.java
package com.example.gouwuche; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.example.gouwuche.model.bean.CartBean; import com.example.gouwuche.model.bean.CountPriceBean; import com.example.gouwuche.presenter.CartPresenter; import com.example.gouwuche.util.ApiUtil; import com.example.gouwuche.view.IView.IMainActivity; import com.example.gouwuche.view.adapter.MyAdapter; import com.example.gouwuche.view.custom.CartExpanableListview; /** * 本购物车采用的是实时更改网络状态...并且再获取购物车数据进行展示 */ public class MainActivity extends AppCompatActivity implements IMainActivity, View.OnClickListener{ private CartExpanableListview expanableListview; private CartPresenter cartPresenter; private CheckBox check_all; private TextView text_total; private TextView text_buy; private CartBean cartBean; private RelativeLayout relative_progress; private MyAdapter myAdapter; private LinearLayout linear_bottom; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if (msg.what == 0){ CountPriceBean countPriceBean = (CountPriceBean) msg.obj; text_total.setText("合计:¥"+countPriceBean.getPriceString()); text_buy.setText("去结算("+countPriceBean.getCount()+")"); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cart_activity_layout); check_all = (CheckBox) findViewById(R.id.check_all); text_total = (TextView) findViewById(R.id.text_total); text_buy = (TextView) findViewById(R.id.text_buy); expanableListview = (CartExpanableListview) findViewById(R.id.expanable_listview); relative_progress = (RelativeLayout) findViewById(R.id.relative_progress); linear_bottom = (LinearLayout) findViewById(R.id.linear_layout); //去掉默认的指示器 expanableListview.setGroupIndicator(null); cartPresenter = new CartPresenter(this); //1.点击全选:选中/未选中...调用适配器中的方法...myAdapter.setIsCheckAll(true);来设置所有的一级和二级是否选中,计算 check_all.setOnClickListener(this); text_buy.setOnClickListener(this); } @Override protected void onResume() { super.onResume(); relative_progress.setVisibility(View.VISIBLE); //请求数据 cartPresenter.getCartData(ApiUtil.cartUrl); } @Override public void getSuccessCartData(CartBean cartBean) { relative_progress.setVisibility(View.GONE); this.cartBean = cartBean; if (cartBean != null){ //显示下面的 linear_bottom.setVisibility(View.VISIBLE); //1.根据组中子条目是否选中,,,决定该组是否选中...初始化一下每一组中isGroupCheck这个数据 for (int i = 0;i<cartBean.getData().size();i++){ if (isAllChildInGroupSelected(i)){ //更改i位置 组的选中状态 cartBean.getData().get(i).setGroupChecked(true); } } //2.根据每一个组是否选中的状态,,,初始化全选是否选中 check_all.setChecked(isAllGroupChecked()); //设置适配器 myAdapter = new MyAdapter(MainActivity.this, cartBean,handler,cartPresenter,relative_progress); expanableListview.setAdapter(myAdapter); //展开 for (int i= 0;i<cartBean.getData().size();i++){ expanableListview.expandGroup(i); } //3.根据子条目是否选中 初始化价格和数量 myAdapter.sendPriceAndCount(); }else { //隐藏下面的全选.... 等 linear_bottom.setVisibility(View.GONE); //显示去逛逛,,,添加购物车 Toast.makeText(MainActivity.this,"购物车为空,去逛逛",Toast.LENGTH_SHORT).show(); } } /** * 所有的一级列表是否选中 */ private boolean isAllGroupChecked() { for (int i =0;i<cartBean.getData().size();i++){ if (! cartBean.getData().get(i).isGroupChecked()){//代表一级列表有没选中的 return false; } } return true; } /** * 判断当前组里面所有的子条目是否选中 * @param groupPosition * @return */ private boolean isAllChildInGroupSelected(int groupPosition) { for (int i= 0;i<cartBean.getData().get(groupPosition).getList().size();i++){ //只要有一个没选中就返回false if (cartBean.getData().get(groupPosition).getList().get(i).getSelected() ==0){ return false; } } return true; } @Override public void onClick(View view) { switch (view.getId()){ case R.id.check_all: myAdapter.setAllChildState(check_all.isChecked()); break; case R.id.text_buy://去结算...试一下创建订单 break; } } }application packger
DashApplication.javapackage com.example.gouwuche.application; import android.app.Application; import android.content.Context; import android.os.Handler; import android.os.Process; /** * Created by Dash on 2017/12/6. */ public class DashApplication extends Application { private static Context context; private static Handler handler; private static int mainId; public static boolean isLoginSuccess;//是否已经登录的状态 @Override public void onCreate() { super.onCreate(); //关于context----http://blog.csdn.net/lmj623565791/article/details/40481055 context = getApplicationContext(); //初始化handler handler = new Handler(); //主线程的id mainId = Process.myTid(); } /** * 对外提供了context * @return */ public static Context getAppContext() { return context; } /** * 得到全局的handler * @return */ public static Handler getAppHanler() { return handler; } /** * 获取主线程id * @return */ public static int getMainThreadId() { return mainId; } }
model packger
CartModel.java
package com.example.gouwuche.model; import android.util.Log; import com.example.gouwuche.model.bean.CartBean; import com.example.gouwuche.presenter.interfac.ICartPresenter; import com.example.gouwuche.util.CommonUtils; import com.example.gouwuche.util.OkHttp3Util; import com.google.gson.Gson; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by Dash on 2017/12/12. */ public class CartModel { private ICartPresenter iCartPresenter; public CartModel(ICartPresenter iCartPresenter) { this.iCartPresenter = iCartPresenter; } public void getCartData(final String cartUrl) { //获取数据 OkHttp3Util.doGet(cartUrl, new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(cartUrl,e.getLocalizedMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ final String json = response.body().string(); CommonUtils.runOnUIThread(new Runnable() { @Override public void run() { /*if ("null".equals(json)){ Toast.makeText(DashApplication.getAppContext(),"购物车为空,请添加",Toast.LENGTH_SHORT).show(); }else {*/ Gson gson = new Gson(); CartBean cartBean = gson.fromJson(json, CartBean.class); //返回数据到主线程 iCartPresenter.getSuccessCartJson(cartBean); //} } }); } } }); } }model bean packger
CartBean.java
package com.example.gouwuche.model.bean; import java.util.List; /** * Created by Dash on 2017/12/12. */ public class CartBean { /** * msg : 请求成功 * code : 0 * data : [{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":22,"price":799,"pscid":1,"selected":0,"sellerid":15,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家15","sellerid":"15"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":1,"price":118,"pscid":1,"selected":0,"sellerid":17,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家17","sellerid":"17"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":2,"price":299,"pscid":1,"selected":0,"sellerid":18,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家18","sellerid":"18"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":4,"price":999,"pscid":1,"selected":0,"sellerid":20,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家20","sellerid":"20"}] */ 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 { public boolean isGroupChecked() { return isGroupChecked; } public void setGroupChecked(boolean groupChecked) { isGroupChecked = groupChecked; } /** * list : [{"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":22,"price":799,"pscid":1,"selected":0,"sellerid":15,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}] * sellerName : 商家15 * sellerid : 15 */ private boolean isGroupChecked;//一级列表是否选中 private String sellerName; private String sellerid; private List<ListBean> list; public String getSellerName() { return sellerName; } public void setSellerName(String sellerName) { this.sellerName = sellerName; } public String getSellerid() { return sellerid; } public void setSellerid(String sellerid) { this.sellerid = sellerid; } public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class ListBean { /** * bargainPrice : 111.99 * createtime : 2017-10-14T21:48:08 * detailUrl : https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends * images : https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg * num : 1 * pid : 22 * price : 799.0 * pscid : 1 * selected : 0 * sellerid : 15 * subhead : 每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下 * title : 北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g */ private double bargainPrice; private String createtime; private String detailUrl; private String images; private int num; private int pid; private double price; private int pscid; private int selected;//判断二级是否选中,,,1选中,0未选中 private int sellerid; private String subhead; private String title; public double getBargainPrice() { return bargainPrice; } public void setBargainPrice(double bargainPrice) { this.bargainPrice = bargainPrice; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public String getDetailUrl() { return detailUrl; } public void setDetailUrl(String detailUrl) { this.detailUrl = detailUrl; } public String getImages() { return images; } public void setImages(String images) { this.images = images; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getPscid() { return pscid; } public void setPscid(int pscid) { this.pscid = pscid; } public int getSelected() { return selected; } public void setSelected(int selected) { this.selected = selected; } public int getSellerid() { return sellerid; } public void setSellerid(int sellerid) { this.sellerid = sellerid; } public String getSubhead() { return subhead; } public void setSubhead(String subhead) { this.subhead = subhead; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } } }CountPriceBean.java
package com.example.gouwuche.model.bean; /** * Created by Dash on 2017/12/19. */ public class CountPriceBean { private String priceString; private int count; public CountPriceBean(String priceString, int count) { this.priceString = priceString; this.count = count; } public String getPriceString() { return priceString; } public void setPriceString(String priceString) { this.priceString = priceString; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }presenter packger
CartPresenter.javapackage com.example.gouwuche.presenter; import com.example.gouwuche.model.CartModel; import com.example.gouwuche.model.bean.CartBean; import com.example.gouwuche.presenter.interfac.ICartPresenter; import com.example.gouwuche.view.IView.IMainActivity; /** * Created by Dash on 2017/12/12. */ public class CartPresenter implements ICartPresenter { private final CartModel cartModel; private IMainActivity iMainActivity; public CartPresenter(IMainActivity iMainActivity) { this.iMainActivity = iMainActivity; cartModel = new CartModel(this); } public void getCartData(String cartUrl) { cartModel.getCartData(cartUrl); } @Override public void getSuccessCartJson(CartBean cartBean) { //回调给view iMainActivity.getSuccessCartData(cartBean); } }presenter interfac packger
ICartPresenter 接口package com.example.gouwuche.presenter.interfac; import com.example.gouwuche.model.bean.CartBean; /** * Created by Dash on 2017/12/12. */ public interface ICartPresenter { void getSuccessCartJson(CartBean cartBean); }
util packgerApiUtil.javapackage com.example.gouwuche.util; /** * Created by Dash on 2017/12/17. */ public class ApiUtil { public static final String cartUrl = "https://www.zhaoapi.cn/product/getCarts?uid=3690"; public static final String addCartUrl = "https://www.zhaoapi.cn/product/addCart";//uid,pid public static final String deleteCartUrl = "https://www.zhaoapi.cn/product/deleteCart";//uid,pid //?uid=71&sellerid=1&pid=1&selected=0&num=10 public static final String updateCartUrl = "https://www.zhaoapi.cn/product/updateCarts"; public static final String createCartUrl = "https://www.zhaoapi.cn/product/createOrder"; }CommonUtils.java
package com.example.gouwuche.util; /** * Created by Dash */ import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.view.View; import com.example.gouwuche.application.DashApplication; /** * Created by Dash */ public class CommonUtils { public static final String TAG = "Dash";//sp文件的xml名称 private static SharedPreferences sharedPreferences; /** * DashApplication.getAppContext()可以使用,但是会使用系统默认的主题样式,如果你自定义了某些样式可能不会被使用 * @param layoutId * @return */ public static View inflate(int layoutId) { View view = View.inflate(DashApplication.getAppContext(), layoutId, null); return view; } /** * dip---px * * @param dip 设备独立像素device independent px....1dp = 3px 1dp = 2px 1dp = 1.5px * @return */ public static int dip2px(int dip) { //获取像素密度 float density = DashApplication.getAppContext().getResources().getDisplayMetrics().density; // int px = (int) (dip * density + 0.5f);//100.6 return px; } /** * px-dip * * @param px * @return */ public static int px2dip(int px) { //获取像素密度 float density = DashApplication.getAppContext().getResources().getDisplayMetrics().density; // int dip = (int) (px / density + 0.5f); return dip; } /** * 获取资源中的字符串 * @param stringId * @return */ public static String getString(int stringId) { return DashApplication.getAppContext().getResources().getString(stringId); } public static Drawable getDrawable(int did) { return DashApplication.getAppContext().getResources().getDrawable(did); } public static int getDimens(int id) { return DashApplication.getAppContext().getResources().getDimensionPixelSize(id); } /** * sp存入字符串类型的值 * @param flag * @param str */ public static void saveSp(String flag, String str) { if (sharedPreferences == null) { sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE); } SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putString(flag, str); edit.commit(); } public static String getSp(String flag) { if (sharedPreferences == null) { sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE); } return sharedPreferences.getString(flag, ""); } public static boolean getBoolean(String tag) { if (sharedPreferences == null) { sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE); } return sharedPreferences.getBoolean(tag, false); } public static void putBoolean(String tag, boolean content) { if (sharedPreferences == null) { sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE); } SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putBoolean(tag, content); edit.commit(); } /** * 清除sp数据 * @param tag */ public static void clearSp(String tag) { if (sharedPreferences == null) { sharedPreferences = DashApplication.getAppContext().getSharedPreferences(TAG, DashApplication.getAppContext().MODE_PRIVATE); } SharedPreferences.Editor edit = sharedPreferences.edit(); edit.remove(tag); edit.commit(); } /** * 自己写的运行在主线程的方法 * 如果是主线程,执行任务,否则使用handler发送到主线程中去执行 * * * @param runable */ public static void runOnUIThread(Runnable runable) { //先判断当前属于子线程还是主线程 if (android.os.Process.myTid() == DashApplication.getMainThreadId()) { runable.run(); } else { //子线程 DashApplication.getAppHanler().post(runable); } } }OkHttp3Util.javapackage com.example.gouwuche.util; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Created by Dash on 2017/12/8. */ public class OkHttp3Util { /** * 懒汉 安全 加同步 * 私有的静态成员变量 只声明不创建 * 私有的构造方法 * 提供返回实例的静态方法 */ private static OkHttpClient okHttpClient = null; private OkHttp3Util() { } public static OkHttpClient getInstance() { if (okHttpClient == null) { //加同步安全 synchronized (OkHttp3Util.class) { if (okHttpClient == null) { //okhttp可以缓存数据....指定缓存路径 File sdcache = new File(Environment.getExternalStorageDirectory(), "cache"); //指定缓存大小 int cacheSize = 10 * 1024 * 1024; okHttpClient = new OkHttpClient.Builder()//构建器 .connectTimeout(15, TimeUnit.SECONDS)//连接超时 .writeTimeout(20, TimeUnit.SECONDS)//写入超时 .readTimeout(20, TimeUnit.SECONDS)//读取超时 //.addInterceptor(new CommonParamsInterceptor())//添加的是应用拦截器...公共参数 //.addNetworkInterceptor(new CacheInterceptor())//添加的网络拦截器 .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))//设置缓存 .build(); } } } return okHttpClient; } /** * get请求 * 参数1 url * 参数2 回调Callback */ public static void doGet(String oldUrl, Callback callback) { //要添加的公共参数...map Map<String,String> map = new HashMap<>(); map.put("source","android"); StringBuilder stringBuilder = new StringBuilder();//创建一个stringBuilder stringBuilder.append(oldUrl); if (oldUrl.contains("?")){ //?在最后面....2类型 if (oldUrl.indexOf("?") == oldUrl.length()-1){ }else { //3类型...拼接上& stringBuilder.append("&"); } }else { //不包含? 属于1类型,,,先拼接上?号 stringBuilder.append("?"); } //添加公共参数.... for (Map.Entry<String,String> entry: map.entrySet()) { //拼接 stringBuilder.append(entry.getKey()) .append("=") .append(entry.getValue()) .append("&"); } //删掉最后一个&符号 if (stringBuilder.indexOf("&") != -1){ stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&")); } String newUrl = stringBuilder.toString();//新的路径 //创建OkHttpClient请求对象 OkHttpClient okHttpClient = getInstance(); //创建Request Request request = new Request.Builder().url(newUrl).build(); //得到Call对象 Call call = okHttpClient.newCall(request); //执行异步请求 call.enqueue(callback); } /** * post请求 * 参数1 url * 参数2 Map<String, String> params post请求的时候给服务器传的数据 * add..("","") * add() */ public static void doPost(String url, Map<String, String> params, Callback callback) { //要添加的公共参数...map Map<String,String> map = new HashMap<>(); map.put("source","android"); //创建OkHttpClient请求对象 OkHttpClient okHttpClient = getInstance(); //3.x版本post请求换成FormBody 封装键值对参数 FormBody.Builder builder = new FormBody.Builder(); //遍历集合 for (String key : params.keySet()) { builder.add(key, params.get(key)); } //添加公共参数 for (Map.Entry<String,String> entry: map.entrySet()) { builder.add(entry.getKey(),entry.getValue()); } //创建Request Request request = new Request.Builder().url(url).post(builder.build()).build(); Call call = okHttpClient.newCall(request); call.enqueue(callback); } /** * post请求上传文件....包括图片....流的形式传任意文件... * 参数1 url * file表示上传的文件 * fileName....文件的名字,,例如aaa.jpg * params ....传递除了file文件 其他的参数放到map集合 * */ public static void uploadFile(String url, File file, String fileName,Map<String,String> params) { //创建OkHttpClient请求对象 OkHttpClient okHttpClient = getInstance(); MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM); //参数 if (params != null){ for (String key : params.keySet()){ builder.addFormDataPart(key,params.get(key)); } } //文件...参数name指的是请求路径中所接受的参数...如果路径接收参数键值是fileeeee,此处应该改变 builder.addFormDataPart("file",fileName,RequestBody.create(MediaType.parse("application/octet-stream"),file)); //构建 MultipartBody multipartBody = builder.build(); //创建Request Request request = new Request.Builder().url(url).post(multipartBody).build(); //得到Call Call call = okHttpClient.newCall(request); //执行请求 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e("upload",e.getLocalizedMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { //上传成功回调 目前不需要处理 if (response.isSuccessful()){ String s = response.body().string(); Log.e("upload","上传--"+s); } } }); } /** * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"} * 参数一:请求Url * 参数二:请求的JSON * 参数三:请求回调 */ public static void doPostJson(String url, String jsonParams, Callback callback) { RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams); Request request = new Request.Builder().url(url).post(requestBody).build(); Call call = getInstance().newCall(request); call.enqueue(callback); } /** * 下载文件 以流的形式把apk写入的指定文件 得到file后进行安装 * 参数er:请求Url * 参数san:保存文件的文件夹....download */ public static void download(final Activity context, final String url, final String saveDir) { Request request = new Request.Builder().url(url).build(); Call call = getInstance().newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { //com.orhanobut.logger.Logger.e(e.getLocalizedMessage()); } @Override public void onResponse(Call call, final Response response) throws IOException { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; try { is = response.body().byteStream();//以字节流的形式拿回响应实体内容 //apk保存路径 final String fileDir = isExistDir(saveDir); //文件 File file = new File(fileDir, getNameFromUrl(url)); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); context.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(context, "下载成功:" + fileDir + "," + getNameFromUrl(url), Toast.LENGTH_SHORT).show(); } }); //apk下载完成后 调用系统的安装方法 Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); context.startActivity(intent); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) is.close(); if (fos != null) fos.close(); } } }); } /** * 判断下载目录是否存在......并返回绝对路径 * * @param saveDir * @return * @throws IOException */ public static String isExistDir(String saveDir) throws IOException { // 下载位置 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir); if (!downloadFile.mkdirs()) { downloadFile.createNewFile(); } String savePath = downloadFile.getAbsolutePath(); Log.e("savePath", savePath); return savePath; } return null; } /** * @param url * @return 从下载连接中解析出文件名 */ private static String getNameFromUrl(String url) { return url.substring(url.lastIndexOf("/") + 1); } /** * 公共参数拦截器 */ private static class CommonParamsInterceptor implements Interceptor{ //拦截的方法 @Override public Response intercept(Chain chain) throws IOException { //获取到请求 Request request = chain.request(); //获取请求的方式 String method = request.method(); //获取请求的路径 String oldUrl = request.url().toString(); Log.e("---拦截器",request.url()+"---"+request.method()+"--"+request.header("User-agent")); //要添加的公共参数...map Map<String,String> map = new HashMap<>(); map.put("source","android"); if ("GET".equals(method)){ // 1.http://www.baoidu.com/login --------? key=value&key=value // 2.http://www.baoidu.com/login? --------- key=value&key=value // 3.http://www.baoidu.com/login?mobile=11111 -----&key=value&key=value StringBuilder stringBuilder = new StringBuilder();//创建一个stringBuilder stringBuilder.append(oldUrl); if (oldUrl.contains("?")){ //?在最后面....2类型 if (oldUrl.indexOf("?") == oldUrl.length()-1){ }else { //3类型...拼接上& stringBuilder.append("&"); } }else { //不包含? 属于1类型,,,先拼接上?号 stringBuilder.append("?"); } //添加公共参数.... for (Map.Entry<String,String> entry: map.entrySet()) { //拼接 stringBuilder.append(entry.getKey()) .append("=") .append(entry.getValue()) .append("&"); } //删掉最后一个&符号 if (stringBuilder.indexOf("&") != -1){ stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&")); } String newUrl = stringBuilder.toString();//新的路径 //拿着新的路径重新构建请求 request = request.newBuilder() .url(newUrl) .build(); }else if ("POST".equals(method)){ //先获取到老的请求的实体内容 RequestBody oldRequestBody = request.body();//....之前的请求参数,,,需要放到新的请求实体内容中去 //如果请求调用的是上面doPost方法 if (oldRequestBody instanceof FormBody){ FormBody oldBody = (FormBody) oldRequestBody; //构建一个新的请求实体内容 FormBody.Builder builder = new FormBody.Builder(); //1.添加老的参数 for (int i=0;i<oldBody.size();i++){ builder.add(oldBody.name(i),oldBody.value(i)); } //2.添加公共参数 for (Map.Entry<String,String> entry:map.entrySet()) { builder.add(entry.getKey(),entry.getValue()); } FormBody newBody = builder.build();//新的请求实体内容 //构建一个新的请求 request = request.newBuilder() .url(oldUrl) .post(newBody) .build(); } } Response response = chain.proceed(request); return response; } } /** * 网络缓存的拦截器......注意在这里更改cache-control头是很危险的,一般客户端不进行更改,,,,服务器端直接指定 * * 没网络取缓存的时候,一般都是在数据库或者sharedPerfernce中取出来的 * * * */ /*private static class CacheInterceptor implements Interceptor{ @Override public Response intercept(Chain chain) throws IOException { //老的响应 Response oldResponse = chain.proceed(chain.request()); *//*if (NetUtils.isNetworkConnected(DashApplication.getAppContext())){ int maxAge = 120; // 在线缓存在2分钟内可读取 return oldResponse.newBuilder() .removeHeader("Pragma") .removeHeader("Cache-Control") .header("Cache-Control", "public, max-age=" + maxAge) .build(); }else { int maxStale = 60 * 60 * 24 * 14; // 离线时缓存保存2周 return oldResponse.newBuilder() .removeHeader("Pragma") .removeHeader("Cache-Control") .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale) .build(); }*//* } }*/ }view adapter packgerMyAdapter.java
package com.example.gouwuche.view.adapter; import android.content.Context; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.gouwuche.R; import com.example.gouwuche.model.bean.CartBean; import com.example.gouwuche.model.bean.CountPriceBean; import com.example.gouwuche.presenter.CartPresenter; import com.example.gouwuche.util.ApiUtil; import com.example.gouwuche.util.OkHttp3Util; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by Dash on 2017/12/18. * * -------------------注意 价格计算的是打折价格 bargin price----------- * */ public class MyAdapter extends BaseExpandableListAdapter{ private RelativeLayout relative_progress; private CartPresenter cartPresenter; private Handler handler; private CartBean cartBean; private Context context; private int size; private int childI; private int allSize; private int index; public MyAdapter(Context context, CartBean cartBean, Handler handler, CartPresenter cartPresenter, RelativeLayout relative_progress) { this.context = context; this.cartBean = cartBean; this.handler = handler; this.cartPresenter = cartPresenter; this.relative_progress = relative_progress; } @Override public int getGroupCount() { return cartBean.getData().size(); } @Override public int getChildrenCount(int groupPosition) { return cartBean.getData().get(groupPosition).getList().size(); } @Override public Object getGroup(int groupPosition) { return cartBean.getData().get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return cartBean.getData().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 true; } @Override public View getGroupView(int groupPosition, boolean b, View view, ViewGroup viewGroup) { final GroupHolder holder; if (view == null){ view = View.inflate(context, R.layout.group_item_layout,null); holder = new GroupHolder(); holder.check_group = (CheckBox) view.findViewById(R.id.check_group); holder.text_group = (TextView) view.findViewById(R.id.text_group); view.setTag(holder); }else { holder = (GroupHolder) view.getTag(); } final CartBean.DataBean dataBean = cartBean.getData().get(groupPosition); //赋值 holder.check_group.setChecked(dataBean.isGroupChecked()); holder.text_group.setText(dataBean.getSellerName()); //组的点击事件...也要去请求更新的接口 holder.check_group.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { relative_progress.setVisibility(View.VISIBLE);//显示 size = dataBean.getList().size(); childI = 0; updateAllInGroup(holder.check_group.isChecked(),dataBean); } }); return view; } /** * 更新一组的状态 * @param checked * @param dataBean */ private void updateAllInGroup(final boolean checked, final CartBean.DataBean dataBean) { CartBean.DataBean.ListBean listBean = dataBean.getList().get(childI);//0 //?uid=71&sellerid=1&pid=1&selected=0&num=10 Map<String, String> params = new HashMap<>(); params.put("uid","3690"); params.put("sellerid", String.valueOf(listBean.getSellerid())); params.put("pid", String.valueOf(listBean.getPid())); params.put("selected", String.valueOf(checked ? 1:0)); params.put("num", String.valueOf(listBean.getNum())); OkHttp3Util.doPost(ApiUtil.updateCartUrl, params, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ childI = childI+1;//0,1,2...3 if (childI <size){ updateAllInGroup(checked,dataBean); }else { //所有的条目已经更新完成....再次请求查询购物车的数据 cartPresenter.getCartData(ApiUtil.cartUrl); } } } }); } @Override public View getChildView(int groupPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) { ChildHolder holder; if (view == null){ view = View.inflate(context, R.layout.child_item_layout,null); holder = new ChildHolder(); holder.text_add = (TextView) view.findViewById(R.id.text_add); holder.text_num = (TextView) view.findViewById(R.id.text_num); holder.text_jian = (TextView) view.findViewById(R.id.text_jian); holder.text_title = (TextView) view.findViewById(R.id.text_title); holder.text_price = (TextView) view.findViewById(R.id.text_price); holder.image_good = (ImageView) view.findViewById(R.id.image_good); holder.check_child = (CheckBox) view.findViewById(R.id.check_child); holder.text_delete = (TextView) view.findViewById(R.id.text_delete); view.setTag(holder); }else { holder = (ChildHolder) view.getTag(); } //赋值 final CartBean.DataBean.ListBean listBean = cartBean.getData().get(groupPosition).getList().get(childPosition); holder.text_num.setText(listBean.getNum()+"");//......注意 holder.text_price.setText("¥"+listBean.getBargainPrice()); holder.text_title.setText(listBean.getTitle()); //listBean.getSelected().....0false,,,1true //设置checkBox选中状态 holder.check_child.setChecked(listBean.getSelected()==0? false:true); /*implementation 'com.github.bumptech.glide:glide:4.4.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.4.0'*/ Glide.with(context).load(listBean.getImages().split("\\|")[0]).into(holder.image_good); //点击事件 holder.check_child.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //点击的时候 更新当前条目选中的状态,,,更新完之后,请求查询购物车,重新展示数据 updateChildChecked(listBean); } }); //加号 holder.text_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //请求更新的接口 updateChildNum(listBean,true); } }); //减号 holder.text_jian.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (listBean.getNum() == 1){ return; } //更新数量,,,减 updateChildNum(listBean,false); } }); return view; } /** * 更新数量 * @param listBean * @param */ private void updateChildNum(CartBean.DataBean.ListBean listBean, boolean isAdded) { //一旦执行更新的操作,,,progressBar显示 relative_progress.setVisibility(View.VISIBLE); //?uid=71&sellerid=1&pid=1&selected=0&num=10 Map<String, String> params = new HashMap<>(); params.put("uid","3690"); params.put("sellerid", String.valueOf(listBean.getSellerid())); params.put("pid", String.valueOf(listBean.getPid())); params.put("selected", String.valueOf(listBean.getSelected())); if (isAdded){ params.put("num", String.valueOf(listBean.getNum() + 1)); }else { params.put("num", String.valueOf(listBean.getNum() - 1)); } OkHttp3Util.doPost(ApiUtil.updateCartUrl, params, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { //更新成功之后...网络上的数据发生了改变...再次请求购物车的接口进行数据的展示 if (response.isSuccessful()){ cartPresenter.getCartData(ApiUtil.cartUrl); } } }); } /** * 更新子条目 网络上的状态 * @param listBean */ private void updateChildChecked(CartBean.DataBean.ListBean listBean) { //一旦执行更新的操作,,,progressBar显示 relative_progress.setVisibility(View.VISIBLE); //?uid=71&sellerid=1&pid=1&selected=0&num=10 Map<String, String> params = new HashMap<>(); params.put("uid","3690"); params.put("sellerid", String.valueOf(listBean.getSellerid())); params.put("pid", String.valueOf(listBean.getPid())); params.put("selected", String.valueOf(listBean.getSelected() == 0? 1:0)); params.put("num", String.valueOf(listBean.getNum())); OkHttp3Util.doPost(ApiUtil.updateCartUrl, params, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { //更新成功之后...网络上的数据发生了改变...再次请求购物车的接口进行数据的展示 if (response.isSuccessful()){ cartPresenter.getCartData(ApiUtil.cartUrl); } } }); } @Override public boolean isChildSelectable(int i, int i1) { return true; } /** * 计算价格和数量 并发送显示 */ public void sendPriceAndCount() { double price = 0; int count = 0; //通过判断二级列表是否勾选,,,,计算价格数量 for (int i=0;i<cartBean.getData().size();i++){ for (int j = 0;j<cartBean.getData().get(i).getList().size();j++){ if (cartBean.getData().get(i).getList().get(j).getSelected() == 1){ //价格是打折的价格........... price += cartBean.getData().get(i).getList().get(j).getNum() * cartBean.getData().get(i).getList().get(j).getBargainPrice(); count += cartBean.getData().get(i).getList().get(j).getNum(); } } } //精准的保留double的两位小数 DecimalFormat decimalFormat = new DecimalFormat("#.00"); String priceString = decimalFormat.format(price); CountPriceBean countPriceBean = new CountPriceBean(priceString, count); //发送...显示 Message msg = Message.obtain(); msg.what = 0; msg.obj = countPriceBean; handler.sendMessage(msg); } /** * 根据全选的状态,,,,跟新每一个子条目的状态,,,全部更新完成后,查询购物车的数据进行展示 * @param checked */ public void setAllChildState(boolean checked) { //创建一个集合 装所有的子条目 List<CartBean.DataBean.ListBean> allList = new ArrayList<>(); for (int i=0;i<cartBean.getData().size();i++){ for (int j=0;j<cartBean.getData().get(i).getList().size();j++){ allList.add(cartBean.getData().get(i).getList().get(j)); } } relative_progress.setVisibility(View.VISIBLE); allSize = allList.size(); index = 0; //通过 递归 更新所有子条目的选中 updateAllChild(allList,checked); } /** * 根据全选 跟新所有的子条目 * @param allList * @param checked */ private void updateAllChild(final List<CartBean.DataBean.ListBean> allList, final boolean checked) { CartBean.DataBean.ListBean listBean = allList.get(index);//0 //跟新的操作 //?uid=71&sellerid=1&pid=1&selected=0&num=10 Map<String, String> params = new HashMap<>(); params.put("uid","3690"); params.put("sellerid", String.valueOf(listBean.getSellerid())); params.put("pid", String.valueOf(listBean.getPid())); params.put("selected", String.valueOf(checked ? 1:0)); params.put("num", String.valueOf(listBean.getNum())); OkHttp3Util.doPost(ApiUtil.updateCartUrl, params, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ index = index +1;//0,1,2......3 if (index < allSize){ updateAllChild(allList,checked); }else { //查询购物车 cartPresenter.getCartData(ApiUtil.cartUrl); } } } }); } private class GroupHolder{ CheckBox check_group; TextView text_group; } private class ChildHolder{ CheckBox check_child; ImageView image_good; TextView text_title; TextView text_price; TextView text_jian; TextView text_num; TextView text_add; TextView text_delete; } }view custom packger
CartExpanableListview.java
package com.example.gouwuche.view.custom; import android.content.Context; import android.util.AttributeSet; import android.widget.ExpandableListView; /** * Created by Dash on 2017/12/12. */ public class CartExpanableListview extends ExpandableListView { public CartExpanableListview(Context context) { super(context); } public CartExpanableListview(Context context, AttributeSet attrs) { super(context, attrs); } public CartExpanableListview(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, height); } }
view iview packger
IMainActivity 接口package com.example.gouwuche.view.IView; import com.example.gouwuche.model.bean.CartBean; /** * Created by Dash on 2017/12/12. */ public interface IMainActivity { void getSuccessCartData(CartBean cartBean); }