首先我们将依赖写入项目的builder
compile 'com.squareup.okhttp3:okhttp:3.9.0' compile 'com.google.code.gson:gson:2.4' compile 'com.github.bumptech.glide:glide:3.7.0' compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
接下来写我们网络请求权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
我们使用MVP方式写购物车 我们代码框架搭好。
首先是请求数据在model层
public class GetCartModel implements GetCartService { private Handler handler = new Handler(Looper.getMainLooper()); @Override public void getCart(Map<String, String> params, final OnNetListener<GetCartBean> onNetListener) { OkHttpUtils.getOkHttpUtils().doPost(Api.str2, params, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); final GetCartBean getCartBean = new Gson().fromJson(string, GetCartBean.class); handler.post(new Runnable() { @Override public void run() { onNetListener.onSuccess(getCartBean); } }); } }); } }
接下来我们定一个接口将我们数据传输
public interface GetCartService { void getCart(Map<String, String> params, OnNetListener<GetCartBean> onNetListener); }
将我们的bean实现
import java.util.List; public class GetCartBean { /** * 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":2,"pid":9,"price":78.99,"pscid":1,"selected":0,"sellerid":2,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家2","sellerid":"2"},{"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":3,"pid":10,"price":555.55,"pscid":1,"selected":0,"sellerid":3,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家3","sellerid":"3"},{"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":11,"price":8989,"pscid":1,"selected":0,"sellerid":4,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家4","sellerid":"4"},{"list":[{"bargainPrice":11800,"createtime":"2017-10-14T21:38:26","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","num":1,"pid":69,"price":16999,"pscid":40,"selected":0,"sellerid":13,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家13","sellerid":"13"},{"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":13,"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: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":5,"price":88.99,"pscid":1,"selected":0,"sellerid":21,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家21","sellerid":"21"},{"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":7,"price":120.01,"pscid":1,"selected":0,"sellerid":23,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家23","sellerid":"23"}] */ 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 { /** * 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":2,"pid":9,"price":78.99,"pscid":1,"selected":0,"sellerid":2,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}] * sellerName : 商家2 * sellerid : 2 */ private boolean checked; private String sellerName; private String sellerid; private List<ListBean> list; public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } 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 : 2 * pid : 9 * price : 78.99 * pscid : 1 * selected : 0 * sellerid : 2 * subhead : 每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下 * title : 北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g */ private boolean checked; private int count = 1; private double bargainPrice; private String createtime; private String detailUrl; private String images; private int num; private int pid; private double price; private int pscid; private int selected; private int sellerid; private String subhead; private String title; public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } 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; } } } }
public class PriceAndCount { private double price; private int count; public PriceAndCount(double price, int count) { this.price = price; this.count = count; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
将我们的OKhttp进行二次封装
public class OkHttpUtils { private static OkHttpUtils okHttpUtils; private final OkHttpClient client; private OkHttpUtils() { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); client = new OkHttpClient.Builder() .addInterceptor(new MyInterceptor()) .build(); } public static OkHttpUtils getOkHttpUtils() { if (okHttpUtils == null) { synchronized (OkHttpUtils.class) { if (okHttpUtils == null) { okHttpUtils = new OkHttpUtils(); } } } return okHttpUtils; } /** * GET请求 * * @param url * @param callback */ public void doGet(String url, Callback callback) { Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(callback); } /** * POST请求 * * @param url * @param params * @param callback */ public void doPost(String url, Map<String, String> params, Callback callback) { if (params == null) { throw new RuntimeException("参数为空了"); } FormBody.Builder builder = new FormBody.Builder(); for (Map.Entry<String, String> entry : params.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } Log.e("OkHttpUtils", "请求地址:" + url + " 请求的参数:"); FormBody formBody = builder.build(); Request request = new Request.Builder().url(url).post(formBody).build(); client.newCall(request).enqueue(callback); } }
public interface OnNetListener<T> { public void onSuccess(T t); public void onFailure(Exception e); }
拦截器import okhttp3.FormBody; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; public class MyInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if (request.method().equals("GET")) { String url = request.url().url().toString(); url += "&source=android"; Request newRequset = request.newBuilder().url(url).build(); return chain.proceed(newRequset); } else { FormBody formBody = (FormBody) request.body(); FormBody.Builder builder = new FormBody.Builder(); for (int i = 0; i < formBody.size(); i++) { builder.add(formBody.name(i), formBody.value(i)); } builder.add("source", "android"); FormBody newFormBody = builder.build(); Request newRequest = request.newBuilder().url(request.url().url().toString()).post(newFormBody).build(); return chain.proceed(newRequest); } } }接口地址public interface Api { boolean ISONLINE = true; String DEV = "http://169.27.23.105"; public static String ONLINE = "http://120.27.23.105"; public static String HOST = ISONLINE ? ONLINE : DEV; public static String Login = HOST + "/user/login"; public static String REGISTER = HOST + "/user/reg"; public static String CATAGORY = HOST + "/product/getCatagory"; public static String PRODUCT_CATAGORY = HOST + "/product/getProductCatagory?cid=%s"; public static String PRODUCT_CATAGORY_LIST = HOST + "/product/getProducts"; public static String PRODUCT_DETAIL = HOST + "/product/getProductDetail?pid=%s&source=android"; public static String ADD_CARD = HOST + "/product/addCart"; public static String SELECT_CARD = HOST + "/product/getCarts"; public static String DEL_CARD = HOST + "/product/deleteCart"; public static String str1 = "https://www.zhaoapi.cn/product/getProductDetail"; public static String str2 = "https://www.zhaoapi.cn/product/getCarts"; }接下来是我们的presenter层import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lijingqian.example.lenovo.myselfe_gouwu.bean.GetCartBean; import lijingqian.example.lenovo.myselfe_gouwu.model.GetCartModel; import lijingqian.example.lenovo.myselfe_gouwu.model.GetCartService; import lijingqian.example.lenovo.myselfe_gouwu.net.OnNetListener; import lijingqian.example.lenovo.myselfe_gouwu.view.ISecondListener; public class GetCartPresenter { private ISecondListener iSecondListener; private final GetCartService getCartService; public GetCartPresenter(ISecondListener iSecondListener) { this.iSecondListener = iSecondListener; getCartService = new GetCartModel(); } public void dettach() { iSecondListener = null; } public void getCart() { Map<String, String> params = new HashMap<>(); params.put("uid", "1234"); params.put("pid", "71"); getCartService.getCart(params, new OnNetListener<GetCartBean>() { @Override public void onSuccess(GetCartBean getCartBean) { if (iSecondListener != null) { List<GetCartBean.DataBean> group = getCartBean.getData(); List<List<GetCartBean.DataBean.ListBean>> child = new ArrayList<>(); for (int i = 0; i < group.size(); i++) { child.add(group.get(i).getList()); } iSecondListener.show(group, child); } } @Override public void onFailure(Exception e) { } }); } }接下来是我们的view层public class MainActivity extends AppCompatActivity implements ISecondListener { private GetCartPresenter getCartPresenter; private ExpandableListView mElv; /** * 全选 */ private CheckBox mCb; /** * 合计: */ private TextView mTvTotal; /** * 去结算(0) */ private TextView mTvCount; private ElvAdapter elvAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); getCartPresenter = new GetCartPresenter(this); getCartPresenter.getCart(); mCb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { elvAdapter.AllOrNone(mCb.isChecked()); } }); } @Override protected void onDestroy() { super.onDestroy(); getCartPresenter.dettach(); } @Override public void show(List<GetCartBean.DataBean> group, List<List<GetCartBean.DataBean.ListBean>> child) { elvAdapter = new ElvAdapter(this, group, child); mElv.setGroupIndicator(null); mElv.setAdapter(elvAdapter); for (int i = 0; i < group.size(); i++) { mElv.expandGroup(i); } } private void initView() { mElv = (ExpandableListView) findViewById(R.id.elv); mCb = (CheckBox) findViewById(R.id.cb); mTvTotal = (TextView) findViewById(R.id.tvTotal); mTvCount = (TextView) findViewById(R.id.tvCount); } public void setPriceAndCount(PriceAndCount priceAndCount) { mTvTotal.setText("合计:" + priceAndCount.getPrice()); mTvCount.setText("去结算(" + priceAndCount.getCount() + ")"); } public void setAllChecked(boolean bool) { mCb.setChecked(bool); } }view层的接口public interface ISecondListener { void show(List<GetCartBean.DataBean> group, List<List<GetCartBean.DataBean.ListBean>> child); }还有我们最重要的adapterpublic class ElvAdapter extends BaseExpandableListAdapter { private Context context; private List<GetCartBean.DataBean> group; private List<List<GetCartBean.DataBean.ListBean>> child; private final LayoutInflater inflater; public ElvAdapter(Context context, List<GetCartBean.DataBean> group, List<List<GetCartBean.DataBean.ListBean>> child) { this.context = context; this.group = group; this.child = child; inflater = LayoutInflater.from(context); } @Override public int getGroupCount() { return group.size(); } @Override public int getChildrenCount(int groupPosition) { return child.get(groupPosition).size(); } @Override public Object getGroup(int groupPosition) { return group.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return child.get(groupPosition).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, ViewGroup parent) { View view; final GroupViewHolder holder; if (convertView == null) { view = inflater.inflate(R.layout.elv_group, null); holder = new GroupViewHolder(); holder.tv = view.findViewById(R.id.tvGroup); holder.cbGroup = view.findViewById(R.id.cbGroup); view.setTag(holder); } else { view = convertView; holder = (GroupViewHolder) view.getTag(); } final GetCartBean.DataBean dataBean = group.get(groupPosition); holder.tv.setText(dataBean.getSellerName()); holder.cbGroup.setChecked(dataBean.isChecked()); holder.cbGroup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //需要改变三个checkbox的状态值 //1.一级列表的checkbox状态值 dataBean.setChecked(holder.cbGroup.isChecked()); //2.二级列表的checkbox状态值 setChildrenCb(groupPosition, holder.cbGroup.isChecked()); //3.全选的checkbox状态值 ((MainActivity) context).setAllChecked(isAllGroupCbChecked()); //计算钱和数量并显示 setPriceAndCount(); //刷新界面 notifyDataSetChanged(); } }); return view; } @Override public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, final View convertView, ViewGroup parent) { View view; final ChildViewHolder holder; if (convertView == null) { view = inflater.inflate(R.layout.elv_child, null); holder = new ChildViewHolder(); holder.iv = view.findViewById(R.id.iv); holder.tvTitle = view.findViewById(R.id.tvTitle); holder.tvSubhead = view.findViewById(R.id.tvSubhead); holder.tvPrice = view.findViewById(R.id.tvPrice); holder.cbChild = view.findViewById(R.id.cbChild); holder.btDel = view.findViewById(R.id.btDel); holder.tvNum = view.findViewById(R.id.tvNum); holder.ivDel = view.findViewById(R.id.ivDel); holder.ivAdd = view.findViewById(R.id.ivAdd); view.setTag(holder); } else { view = convertView; holder = (ChildViewHolder) view.getTag(); } final GetCartBean.DataBean.ListBean listBean = child.get(groupPosition).get(childPosition); String images = listBean.getImages(); Glide.with(context).load(images.split("\\|")[0]).into(holder.iv); holder.tvTitle.setText(listBean.getTitle()); holder.cbChild.setChecked(child.get(groupPosition).get(childPosition).isChecked()); holder.tvSubhead.setText(listBean.getSubhead()); holder.tvPrice.setText(listBean.getPrice() + "元"); holder.tvNum.setText(listBean.getCount() + ""); //给checkbox设置点击事件 holder.cbChild.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //需要改变三个checkbox的状态值 //1.二级列表的checkbox状态值 listBean.setChecked(holder.cbChild.isChecked()); //2.一级列表的checkbox状态值 group.get(groupPosition).setChecked(isAllChildCbChecked(groupPosition)); //3.全选的checkbox状态值 ((MainActivity) context).setAllChecked(isAllGroupCbChecked()); //计算钱和数量并显示 setPriceAndCount(); //刷新界面 notifyDataSetChanged(); } }); holder.ivAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取目前显示的值 int count = listBean.getCount(); count++; //改变JavaBean里的状态值 listBean.setCount(count); //计算钱和数量并显示 setPriceAndCount(); //刷新列表 notifyDataSetChanged(); } }); holder.ivDel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取目前显示的值 int count = listBean.getCount(); if (count <= 1) { count = 1; } else { count--; } //改变JavaBean里的状态值 listBean.setCount(count); //计算钱和数量并显示 setPriceAndCount(); //刷新列表 notifyDataSetChanged(); } }); holder.btDel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //其实就是删除集合 List<GetCartBean.DataBean.ListBean> listBeans = child.get(groupPosition); if (listBeans.size() > 0) { listBeans.remove(childPosition); } if (listBeans.size() == 0) { child.remove(groupPosition); group.remove(groupPosition); } //计算钱和数量并显示 setPriceAndCount(); //改变全选状态 ((MainActivity) context).setAllChecked(isAllGroupCbChecked()); //刷新列表 notifyDataSetChanged(); } }); return view; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } class GroupViewHolder { TextView tv; CheckBox cbGroup; } class ChildViewHolder { ImageView iv; TextView tvTitle; TextView tvSubhead; TextView tvPrice; CheckBox cbChild; Button btDel; TextView tvNum; ImageView ivDel; ImageView ivAdd; } /** * 设置一级列表对应的二级列表checkbox状态 * * @param groupPosition * @param bool */ private void setChildrenCb(int groupPosition, boolean bool) { List<GetCartBean.DataBean.ListBean> listBeans = child.get(groupPosition); for (int i = 0; i < listBeans.size(); i++) { listBeans.get(i).setChecked(bool); } } /** * 判断一级列表checkbox状态 * * @return */ private boolean isAllGroupCbChecked() { if (group.size() == 0) { return false; } for (int i = 0; i < group.size(); i++) { if (!group.get(i).isChecked()) { return false; } } return true; } /** * 判断二级列表checkbox状态 * * @return */ private boolean isAllChildCbChecked(int groupPosition) { List<GetCartBean.DataBean.ListBean> listBeans = child.get(groupPosition); for (int i = 0; i < listBeans.size(); i++) { if (!listBeans.get(i).isChecked()) { return false; } } return true; } /** * 设置钱和数量 */ private void setPriceAndCount() { ((MainActivity) context).setPriceAndCount(compute()); } /** * 计算钱和数量 */ private PriceAndCount compute() { double price = 0; int count = 0; for (int i = 0; i < group.size(); i++) { List<GetCartBean.DataBean.ListBean> listBeans = child.get(i); for (int j = 0; j < listBeans.size(); j++) { if (listBeans.get(j).isChecked()) { price += listBeans.get(j).getPrice() * listBeans.get(j).getCount(); count += listBeans.get(j).getCount(); } } } return new PriceAndCount(price, count); } /** * 全选或者全不选 * * @param bool */ public void AllOrNone(boolean bool) { for (int i = 0; i < group.size(); i++) { group.get(i).setChecked(bool); setChildrenCb(i, bool); } setPriceAndCount(); notifyDataSetChanged(); } }布局文件<ExpandableListView android:id="@+id/elv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="40dp"> <CheckBox android:id="@+id/cb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:text="全选" /> <TextView android:id="@+id/tvTotal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="15dp" android:layout_toRightOf="@id/cb" android:text="合计:" /> <TextView android:id="@+id/tvCount" android:layout_width="100dp" android:layout_height="match_parent" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:background="#ff0000" android:gravity="center" android:text="去结算(0)" android:textColor="#ffffff" /> </RelativeLayout><?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="120dp" android:descendantFocusability="blocksDescendants" android:gravity="center_vertical" android:orientation="horizontal" android:paddingLeft="50dp"> <CheckBox android:id="@+id/cbChild" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/iv" android:layout_width="100dp" android:layout_height="100dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical"> <TextView android:id="@+id/tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/tvSubhead" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/tvSubhead" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:id="@+id/tvPrice" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:layout_marginLeft="10dp" android:id="@+id/ivDel" android:layout_width="25dp" android:layout_height="25dp" android:background="@drawable/iv_del" /> <TextView android:id="@+id/tvNum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp" android:layout_marginLeft="3dp" android:layout_marginRight="3dp" android:text="1"/> <ImageView android:id="@+id/ivAdd" android:layout_width="25dp" android:layout_height="25dp" android:background="@drawable/iv_add" /> </LinearLayout> </LinearLayout> <Button android:id="@+id/btDel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="删除" /><?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/cbGroup" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/tvGroup" android:layout_width="match_parent" android:layout_height="40dp" android:gravity="center_vertical" /> </LinearLayout>这就完成了