依赖就不用说了
下面先来布局吧
activity_main
<?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.daydayup.day14_gouwuche.view.MainActivity">
<ExpandableListView
android:id="@+id/expandable_list_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:groupIndicator="@null"
android:layout_weight="1"></ExpandableListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="@+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="合计:0" />
<Button
android:id="@+id/jisuan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#F00"
android:text="去结算(0)" />
</LinearLayout>
</LinearLayout>
add_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="@drawable/add_shape"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:gravity="center"
android:id="@+id/sub"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/add_shape"
android:text="-" />
<EditText
android:id="@+id/count"
android:layout_width="50dp"
android:layout_height="30dp"
android:background="@null" />
<TextView
android:gravity="center"
android:id="@+id/add"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/add_shape"
android:text="+" />
</LinearLayout>
item_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_pic"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@mipmap/ic_launcher" />
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
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:singleLine="true"
android:text="商品名"
android:textSize="25sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/child_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:text="商品价格"
android:textColor="#F00" />
<com.daydayup.day14_gouwuche.view.custumviews.AddSubView
android:layout_width="100dp"
android:id="@+id/addSubView"
android:layout_height="30dp"></com.daydayup.day14_gouwuche.view.custumviews.AddSubView>
</LinearLayout>
</LinearLayout>
<TextView
android:id="@+id/dele"
android:background="#F00"
android:text="删除"
android:gravity="center"
android:layout_width="50dp"
android:layout_height="match_parent" />
</LinearLayout>
item_parent
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/parent_cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/parent_title"
android:text="商家"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_conten t" />
</LinearLayout>
drawable文件下
add_shape
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="100dp"
android:height="30dp" />
<stroke
android:width="1dp"
android:color="#999999" />
</shape>
Modle层开始
GouWuBean
package com.daydayup.day14_gouwuche.model;
import java.util.List;
/**
* Created by gjl on 2018/4/25.
*/
public class GouWuBean {
/**
* msg : 请求成功
* code : 0
* data : [{"list":[],"sellerName":"","sellerid":"0"},{"list":[{"bargainPrice":11800,"createtime":"2017-10-10T17:33:37","detailUrl":"https://item.m.jd.com/product/4338107.htmlChildBeanutm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6700/155/2098998076/156185/6cf95035/595dd5a5Nc3a7dab5.jpg!q70.jpg","num":2,"pid":57,"price":5199,"pscid":40,"selected":0,"sellerid":1,"subhead":"【i5 MX150 2G显存】全高清窄边框 8G内存 256固态硬盘 支持指纹识别 预装WIN10系统","title":"小米(MI)Air 13.3英寸全金属轻薄笔记本(i5-7200U 8G 256G PCle SSD MX150 2G独显 FHD 指纹识别 Win10)银 "}],"sellerName":"商家1","sellerid":"1"},{"list":[{"bargainPrice":3455,"createtime":"2017-10-03T23:53:28","detailUrl":"https://item.m.jd.com/product/12224420750.htmlChildBeanutm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","num":5,"pid":54,"price":888,"pscid":39,"selected":0,"sellerid":10,"subhead":"【现货新品抢购】全面屏2.0震撼来袭,骁龙835处理器,四曲面陶瓷机","title":"小米(MI) 小米MIX2 手机 黑色 全网通 (6GB+64GB)【标配版】"}],"sellerName":"商家10","sellerid":"10"},{"list":[{"bargainPrice":3455,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/12224420750.htmlChildBeanutm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","num":1,"pid":56,"price":99,"pscid":39,"selected":0,"sellerid":12,"subhead":"【现货新品抢购】全面屏2.0震撼来袭,骁龙835处理器,四曲面陶瓷机","title":"小米(MI) 小米MIX2 手机 黑色 全网通 (6GB+64GB)【标配版】"},{"bargainPrice":11800,"createtime":"2017-10-14T21:48:08","detailUrl":"https://mitem.jd.hk/ware/view.actionChildBeanwareId=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":68,"price":15000,"pscid":40,"selected":0,"sellerid":12,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家12","sellerid":"12"}]
*/
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 : []
* sellerName :
* sellerid : 0
*/
private String sellerName;
private String sellerid;
private List<ChildBean> list;
//状态
private boolean parent_flag;
public boolean isParent_flag() {
return parent_flag;
}
public void setParent_flag(boolean parent_flag) {
this.parent_flag = parent_flag;
}
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{
/**
* bargainPrice : 11800
* createtime : 2017-10-10T17:33:37
* detailUrl : https://item.m.jd.com/product/4338107.htmlChildBeanutm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends
* images : https://m.360buyimg.com/n0/jfs/t6700/155/2098998076/156185/6cf95035/595dd5a5Nc3a7dab5.jpg!q70.jpg
* num : 2
* pid : 57
* price : 5199
* pscid : 40
* selected : 0
* sellerid : 1
* subhead : 【i5 MX150 2G显存】全高清窄边框 8G内存 256固态硬盘 支持指纹识别 预装WIN10系统
* title : 小米(MI)Air 13.3英寸全金属轻薄笔记本(i5-7200U 8G 256G PCle SSD MX150 2G独显 FHD 指纹识别 Win10)银
*/
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;
//是否选中的状态
private boolean child_flag;
public boolean isChild_flag() {
return child_flag;
}
public void setChild_flag(boolean child_flag) {
this.child_flag = child_flag;
}
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;
}
}
}
IModel
package com.daydayup.day14_gouwuche.model;
import java.util.List;
import java.util.Map;
/**
* Model
*
* MVP
* m---获取数据
* v---显示视图
* p---逻辑
*
*/
public interface IModel {
//获取购物车数据
void getGouWuCheData(String url, Map<String,String> map,GouWuCheListener gouWuCheListener);
//计算总价
void jisuan(List<GouWuBean.DataBean> list,JiSuanListener jiSuanListener);
}
ModelImpl
package com.daydayup.day14_gouwuche.model;
import android.util.Log;
import com.daydayup.day14_gouwuche.http.HttpUtils;
import com.daydayup.day14_gouwuche.http.OkLoadListener;
import java.util.List;
import java.util.Map;
/**
* Created by gjl on 2018/4/25.
*/
public class ModelImpl implements IModel {
private static final String TAG = "ModelImpl---";
@Override
public void getGouWuCheData(String url, Map<String, String> map, final GouWuCheListener gouWuCheListener) {
HttpUtils httpUtils = HttpUtils.getHttpUtils();
httpUtils.okPost(url, map);
httpUtils.setOkLoadListener(new OkLoadListener() {
@Override
public void okLoadSuccess(String json) {
Log.d(TAG, "okLoadSuccess: "+json);
gouWuCheListener.getDataSuccess(json);
}
@Override
public void okLoadError(String error) {
Log.d(TAG, "okLoadError: "+error);
gouWuCheListener.getDataError(error);
}
});
}
@Override
public void jisuan(List<GouWuBean.DataBean> list, JiSuanListener jiSuanListener) {
double sum = 0;
for (int i = 0; i < list.size(); i++) {
List<GouWuBean.ChildBean> list_child = list.get(i).getList();
for (int j = 0; j < list_child.size(); j++) {
boolean child_flag = list_child.get(j).isChild_flag();
if (child_flag){
double price = list_child.get(j).getPrice();
sum+=price;
}
}
}
//记得回调
jiSuanListener.jiSuan(sum);
}
}
JiSuanListener
public interface JiSuanListener {
void jiSuan(double price);
}
AddSubView
package com.daydayup.day14_gouwuche.view.custumviews;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.daydayup.day14_gouwuche.R;
/**
* Created by gjl on 2018/4/26.
*/
public class AddSubView extends LinearLayout implements View.OnClickListener {
private TextView add;
private TextView sub;
private EditText count;
public AddSubView(Context context) {
this(context, null);
}
public AddSubView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public AddSubView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
View view = View.inflate(context, R.layout.add_layout, this);
add = view.findViewById(R.id.add);
sub = view.findViewById(R.id.sub);
add.setOnClickListener(this);
sub.setOnClickListener(this);
count = view.findViewById(R.id.count);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
add();
break;
case R.id.sub:
sub();
break;
}
}
//添加
public void add() {
String s = count.getText().toString();
double i = Double.parseDouble(s);
i++;
count.setText(i + "");
}
//减少
public void sub() {
String s = count.getText().toString();
double i = Double.parseDouble(s);
if (i >= 1) {
i--;
count.setText(i + "");
}
}
//设置数量
//获取数量
public String getCount() {
return count.getText().toString();
}
public void setCount(double count1){
count.setText(count1+"");
}
}
IMainView
package com.daydayup.day14_gouwuche.view;
import com.daydayup.day14_gouwuche.model.GouWuBean;
import java.util.List;
/**
* View接口
*/
public interface IMainView {
//显示数据
void showGowWuList(List<GouWuBean.DataBean> list);
//显示总价
void showSum(double price);
//获取集合数据
List<GouWuBean.DataBean> getList();
}
IPresenter
public interface IPresenter {
void showGouWuCheToView(IModel iModel, IMainView iMainView);
//将计算结果显示到view
void showSumToView(IModel iModel, IMainView iMainView);
}
PresenterImpl
public class PresenterImpl implements IPresenter {
private static final String TAG = "PresenterImpl----";
//显示数据
@Override
public void showGouWuCheToView(IModel iModel, final IMainView iMainView) {
Map<String, String> map = new HashMap<>();
map.put("uid", "71");
iModel.getGouWuCheData(HttpConfig.gouwuche_url, map, new GouWuCheListener() {
@Override
public void getDataSuccess(String json) {
Gson gson = new Gson();
GouWuBean gouWuBean = gson.fromJson(json, GouWuBean.class);
List<GouWuBean.DataBean> list = gouWuBean.getData();
//传入view
iMainView.showGowWuList(list);
}
@Override
public void getDataError(String error) {
Log.d(TAG, "error: " + error);
}
});
}
//显示计算结果
@Override
public void showSumToView(IModel iModel, final IMainView iMainView) {
iModel.jisuan(iMainView.getList(), new JiSuanListener() {
@Override
public void jiSuan(double price) {
iMainView.showSum(price);
}
});
}
}
MyAdapter
public class MyAdapter extends BaseExpandableListAdapter {
private Context context;
private List<GouWuBean.DataBean> list;
private IMainView iMainView;
public MyAdapter(Context context, List<GouWuBean.DataBean> list, IMainView iMainView) {
this.list = list;
this.context = context;
this.iMainView = iMainView;
}
@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 true;
}
@Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
ParentViewHolder parentViewHolder = null;
if (convertView == null) {
convertView = View.inflate(context, R.layout.item_parent, null);
CheckBox checkBox = convertView.findViewById(R.id.parent_cb);
TextView textView = convertView.findViewById(R.id.parent_title);
parentViewHolder = new ParentViewHolder(checkBox, textView);
convertView.setTag(parentViewHolder);
} else {
parentViewHolder = (ParentViewHolder) convertView.getTag();
}
//赋值
parentViewHolder.getParent_tv().setText(list.get(groupPosition).getSellerName());
parentViewHolder.getParent_cb().setChecked(list.get(groupPosition).isParent_flag());
//单选框的点击事件
final ParentViewHolder finalParentViewHolder = parentViewHolder;
//点击事件
parentViewHolder.getParent_cb().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isChecked = finalParentViewHolder.getParent_cb().isChecked();
//改变bean里面的值
list.get(groupPosition).setParent_flag(isChecked);
//给子列表赋值
List<GouWuBean.ChildBean> list_child = MyAdapter.this.list.get(groupPosition).getList();
for (int i = 0; i < list_child.size(); i++) {
GouWuBean.ChildBean childBean = list_child.get(i);
//改变bean里面的值
childBean.setChild_flag(isChecked);
}
notifyDataSetChanged();
//调用计算的方法
PresenterImpl presenter = new PresenterImpl();
presenter.showSumToView(new ModelImpl(), iMainView);
}
});
return convertView;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ChildViewHolder childViewHolder = null;
if (convertView == null) {
convertView = View.inflate(context, R.layout.item_child, null);
CheckBox child_cb = convertView.findViewById(R.id.child_cb);
TextView child_title = convertView.findViewById(R.id.child_title);
TextView dele = convertView.findViewById(R.id.dele);
ImageView child_pic = convertView.findViewById(R.id.child_pic);
TextView tv_price = convertView.findViewById(R.id.child_price);
AddSubView addSubView = convertView.findViewById(R.id.addSubView);
childViewHolder = new ChildViewHolder(child_cb, child_pic, child_title, tv_price, addSubView, dele);
convertView.setTag(childViewHolder);
} else {
childViewHolder = (ChildViewHolder) convertView.getTag();
}
//赋值
final List<GouWuBean.ChildBean> child_list = this.list.get(groupPosition).getList();
childViewHolder.getChild_title().setText(child_list.get(childPosition).getTitle());
childViewHolder.getChild_price().setText(child_list.get(childPosition).getPrice() + "");
//给单选框赋值
childViewHolder.getChild_cb().setChecked(child_list.get(childPosition).isChild_flag());
String images = child_list.get(childPosition).getImages();
String pic_url = images.split("\\|")[0];
Glide.with(context).load(pic_url).into(childViewHolder.getChild_pic());
childViewHolder.getAddSubView().setCount(child_list.get(childPosition).getNum());
//字条目单选框的点击事件
final ChildViewHolder finalChildViewHolder = childViewHolder;
childViewHolder.getChild_cb().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取当前条目状态
boolean checked = finalChildViewHolder.getChild_cb().isChecked();
//赋值--改变bean
child_list.get(childPosition).setChild_flag(checked);
//for循环,
boolean flag = true;
for (int i = 0; i < child_list.size(); i++) {
boolean child_flag = child_list.get(i).isChild_flag();
if (child_flag == false) {
flag = false;
}
}
//然后将flag赋值给父条目的bean
list.get(groupPosition).setParent_flag(flag);
notifyDataSetChanged();
//调用计算的方法
PresenterImpl presenter = new PresenterImpl();
presenter.showSumToView(new ModelImpl(), iMainView);
}
});
//删除
childViewHolder.getDelte().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
child_list.remove(childPosition);
notifyDataSetChanged();
}
});
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
//父布局的ViewHolder
public class ParentViewHolder {
private CheckBox parent_cb;
private 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;
}
}
//子布局的ViewHolder
public class ChildViewHolder {
private CheckBox child_cb;
private ImageView child_pic;
private TextView child_title;
private TextView delte;
private TextView child_price;
private AddSubView addSubView;
public ChildViewHolder(CheckBox child_cb, ImageView child_pic, TextView child_title, TextView child_price, AddSubView addSubView, TextView delte) {
this.child_cb = child_cb;
this.child_pic = child_pic;
this.child_title = child_title;
this.child_price = child_price;
this.addSubView = addSubView;
this.delte = delte;
}
public AddSubView getAddSubView() {
return addSubView;
}
public TextView getDelte() {
return delte;
}
public void setDelte(TextView delte) {
this.delte = delte;
}
public void setAddSubView(AddSubView addSubView) {
this.addSubView = addSubView;
}
public CheckBox getChild_cb() {
return child_cb;
}
public void setChild_cb(CheckBox child_cb) {
this.child_cb = child_cb;
}
public ImageView getChild_pic() {
return child_pic;
}
public void setChild_pic(ImageView child_pic) {
this.child_pic = child_pic;
}
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;
}
}
}
三个OK封装类
HttpConfig
public class HttpConfig {
public static String gouwuche_url = "https://www.zhaoapi.cn/product/getCarts";
}
HttpUtils
public class HttpUtils {
private static final String TAG = "HttpUtils-----";
private static HttpUtils httpUtils;
private final int SUCCESS = 0;
private final int ERROR = 1;
private MyHandler myHandler = new MyHandler();
private OkLoadListener okLoadListener;
public static HttpUtils getHttpUtils() {
if (httpUtils == null) {
httpUtils = new HttpUtils();
}
return httpUtils;
}
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SUCCESS:
//成功
String json = (String) msg.obj;
okLoadListener.okLoadSuccess(json);
break;
case ERROR:
//失败
String error = (String) msg.obj;
okLoadListener.okLoadError(error);
break;
}
}
}
//get
public void okGet(String url) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyIntercepter()).build();
Request request = new Request.Builder().url(url).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message = myHandler.obtainMessage();
message.what = ERROR;
message.obj = e.getMessage();
myHandler.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Message message = myHandler.obtainMessage();
message.what = SUCCESS;
message.obj = response.body().string();
myHandler.sendMessage(message);
}
});
}
public void setOkLoadListener(OkLoadListener okLoadListener) {
this.okLoadListener = okLoadListener;
}
//post
public void okPost(String url, Map<String, String> params) {
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyIntercepter()).build();
FormBody.Builder builder = new FormBody.Builder();
Set<String> keySet = params.keySet();
for (String key :
keySet) {
String value = params.get(key);
builder.add(key, value);
}
FormBody formBody = builder.build();
Request request = new Request.Builder().url(url).post(formBody).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Message message = myHandler.obtainMessage();
message.what = ERROR;
message.obj = e.getMessage();
myHandler.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Message message = myHandler.obtainMessage();
message.what = SUCCESS;
message.obj = response.body().string();
myHandler.sendMessage(message);
}
});
}
//拦截器
class MyIntercepter implements Interceptor {
//intercept 拦截
@Override
public Response intercept(Chain chain) throws IOException {
//添加公共参数
//post 取出原来所有的参数,将之加到新的请求体里面。然后让请求去执行
Request request = chain.request();
//获取请求方法
String method = request.method();
if (method.equals("GET")) {//---------------------------GET 拦截
//取出url地址
String url = request.url().toString();
//拼接公共参数
boolean contains = url.contains("?");
if (contains) {
url = url + "&source=android";
} else {
url = url + "?source=android";
}
Request request1 = request.newBuilder().url(url).build();
Response response = chain.proceed(request1);
return response;
} else if (method.equals("POST")) {//---------------------POST 拦截
RequestBody body = request.body();//请求体
if (body instanceof FormBody) {
//创建新的请求体
FormBody.Builder newBuilder = new FormBody.Builder();
for (int i = 0; i < ((FormBody) body).size(); i++) {
String key = ((FormBody) body).name(i);
String value = ((FormBody) body).value(i);
newBuilder.add(key, value);
}
//添加公共参数
newBuilder.add("source", "android");
FormBody newBody = newBuilder.build();
//创建新的请求体
Request request1 = request.newBuilder().post(newBody).build();
//去请求
Response response = chain.proceed(request1);
return response;
}
}
return null;
}
}
//上传文件(图片)
public void upLoadImage(String url, String path) {//url 要上传的地址。path 要上传的文件路径
//媒体类型
MediaType mediaType = MediaType.parse("image/*");
//multipartbody
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
File file = new File(path);
MultipartBody multipartBody = builder.addFormDataPart("file", file.getName(), RequestBody.create(mediaType, file)).build();
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).post(multipartBody).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "上传失败0----: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "上传成功: ");
}
});
}
}
OkLoadListener
public interface OkLoadListener {
void okLoadSuccess(String json);
void okLoadError(String error);
}
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener,IMainView {
private ExpandableListView expandableListView;
private CheckBox checkBox;
private TextView tv_sum;
private Button jisuan;
private static final String TAG = "MainActivity0------";
private List<GouWuBean.DataBean> list_tmp;
private MyAdapter myAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
initViews();
//请求数据
initDatas();
}
private void initDatas() {
PresenterImpl presenter = new PresenterImpl();
presenter.showGouWuCheToView(new ModelImpl(),this);
}
private void initViews() {
expandableListView = findViewById(R.id.expandable_list_view);
checkBox = findViewById(R.id.cb);
tv_sum = findViewById(R.id.tv_sum);
jisuan = findViewById(R.id.jisuan);
checkBox.setOnClickListener(this);
jisuan.setOnClickListener(this);
}
//点击事件
@Override
public void onClick(View v) {
switch (v.getId()) {
//全选,全部选 总价
case R.id.cb:
boolean checked = checkBox.isChecked();
for (int i = 0; i < list_tmp.size(); i++) {
list_tmp.get(i).setParent_flag(checked);
List<GouWuBean.ChildBean> list_child = list_tmp.get(i).getList();
for (int j = 0; j < list_child.size(); j++) {
list_child.get(j).setChild_flag(checked);
}
}
//刷新适配器
myAdapter.notifyDataSetChanged();
//调用计算总价的方法
PresenterImpl presenter = new PresenterImpl();
presenter.showSumToView(new ModelImpl(),this);
break;
case R.id.jisuan:
Toast.makeText(MainActivity.this,"去计算总价",Toast.LENGTH_SHORT).show();
break;
}
}
//展示购物车数据
@Override
public void showGowWuList(List<GouWuBean.DataBean> list) {
list_tmp=list;
Log.d(TAG, "showGowWuList: "+list);
myAdapter = new MyAdapter(MainActivity.this, list,this);
expandableListView.setAdapter(myAdapter);
//展开expandablelistview
int childCount = expandableListView.getCount();
for (int i = 0; i < childCount; i++) {
expandableListView.expandGroup(i);
}
}
//显示总价
@Override
public void showSum(double price) {
tv_sum.setText("合计:"+price);
}
@Override
public List<GouWuBean.DataBean> getList() {
return list_tmp;
}
}