例:
demo下载地址:
//零购物车MyApp
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
ImageLoaderConfiguration build = new ImageLoaderConfiguration.Builder(this).build();
ImageLoader.getInstance().init(build);
//fresco的初始化
Fresco.initialize(this);
}
}
//<uses-permission android:name="android.permission.INTERNET"/>
//android:name=".MyApp"
// compile 'com.android.support:appcompat-v7:25.3.1'
// compile 'com.android.support.constraint:constraint-layout:1.0.2'
// compile 'com.squareup.okhttp3:okhttp:3.4.1'
// compile 'com.google.code.gson:gson:2.8.1'
// compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
// compile 'de.greenrobot:eventbus:3.0.0-beta1'
// testCompile 'junit:junit:4.12'
// compile 'com.android.support:recyclerview-v7:25.3.1'
// compile 'com.facebook.fresco:fresco:1.5.0'
//一购物车MainActivity
public class MainActivity extends AppCompatActivity implements ICart {
private ExpandableListView mElv;
private CheckBox mQuanxuan;
/**
* 总价:0.0
*/
private TextView mZongjia;
private MyAdapter myAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注册
EventBus.getDefault().register(this);
initView();
new CartPersenter(this).getGoods();
mQuanxuan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myAdapter .qx(mQuanxuan.isChecked());
}
});
}
@Override
public void ShowData(List<GoodsBean.DataBean> data, List<List<GoodsBean.DataBean.ListBean>> list) {
myAdapter = new MyAdapter(data,list, this);
mElv.setAdapter(myAdapter);
/* //没有
mElv.setGroupIndicator(null);
//默认展开
for (int i = 0; i < data.size(); i++) {
mElv.expandGroup(i);
}*/
}
private void initView() {
mElv = (ExpandableListView) findViewById(R.id.elv);
mQuanxuan = (CheckBox) findViewById(R.id.quanxuan);
mZongjia = (TextView) findViewById(R.id.zongjia);
TextView viewById = (TextView) findViewById(R.id.yemian);
viewById.setText("购物车");
}
@Subscribe
public void onMessga(MessageEvent event){
//给全选设值
mQuanxuan.setChecked(event.isCheck());
}
@Subscribe
public void onMessga(CountPrice cp){
//给价格和数量设置
mZongjia.setText("总价:"+cp.getPrice());
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
// <?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:orientation="vertical"
// android:layout_height="match_parent"
// tools:context=".MainActivity">
//<include layout="@layout/title"
// android:layout_marginTop="5dp"
// android:layout_width="match_parent"
// android:layout_height="0dp"
// android:layout_weight="1"
// ></include>
//<ExpandableListView
// android:layout_marginLeft="5dp"
// android:id="@+id/elv"
// android:layout_width="match_parent"
// android:layout_height="0dp"
// android:layout_weight="8" />
//<LinearLayout
// android:layout_margin="5dp"
// android:orientation="horizontal"
// android:layout_width="match_parent"
// android:layout_height="0dp"
// android:layout_weight="1">
//<CheckBox
// android:id="@+id/quanxuan"
// android:layout_width="0dp"
// android:layout_weight="1"
// android:layout_height="match_parent" />
//<TextView
// android:layout_marginTop="5dp"
// android:text="全选"
// android:textStyle="bold"
// android:textSize="30dp"
// android:layout_width="0dp"
// android:layout_weight="1"
// android:layout_height="match_parent" />
//<TextView
// android:layout_marginTop="15dp"
// android:textStyle="bold"
// android:textSize="20dp"
// android:id="@+id/zongjia"
// android:textColor="#FFDF1818"
// android:layout_width="0dp"
// android:layout_weight="2"
// android:layout_height="match_parent"
// android:text="总价:0.0" />
//<Button
// android:textStyle="bold"
// android:textSize="20dp"
// android:id="@+id/buttonzf"
// android:layout_width="0dp"
// android:layout_weight="1"
// android:layout_height="match_parent"
// android:text="支付" />
//</LinearLayout>
//</LinearLayout>
// <?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">
//<ImageView
// android:id="@+id/fanhui"
// android:background="@drawable/icon_back"
// android:layout_width="0dp"
// android:layout_weight="1"
// android:layout_height="30dp"
// android:layout_marginTop="8dp"/>
//<TextView
// android:id="@+id/yemian"
// android:gravity="center_horizontal"
// android:textSize="30dp"
// android:textStyle="bold"
// android:textColor="#f000"
// android:layout_width="0dp"
// android:layout_weight="9"
// android:layout_height="match_parent" />
//</LinearLayout>
//public interface ICart {
// void ShowData(List<GoodsBean.DataBean> data, List< List<GoodsBean.DataBean.ListBean>> childlist);
//}
//public class GoodsBean {
// 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 {
// private String sellerName;
// private String sellerid;
// private List<ListBean> list;
// private boolean check;
// public boolean isCheck() {
// return check;
// }
// public void setCheck(boolean check) {
// this.check = check;
// }
// 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 class ListBean{
// private double bargainPrice;
// private String createtime;
// private String detailUrl;
// private String images;
// private int num;
// private double price;
// private String subhead;
// private String title;
// private boolean check;
// public boolean isCheck() {
// return check;
// }
// public void setCheck(boolean check) {
// this.check = check;
// }
// 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 double getPrice() {
// return price;
// }
// public void setPrice(double price) {
// this.price = price;
// }
// 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 MyAdapter extends BaseExpandableListAdapter {
private List<GoodsBean.DataBean> groupdata;
private List< List<GoodsBean.DataBean.ListBean>> childlist;
private Context context;
/**
* @param groupdata
* @param childlist
* @param context
*/
public MyAdapter(List<GoodsBean.DataBean> groupdata, List< List<GoodsBean.DataBean.ListBean>> childlist, Context context) {
this.groupdata = groupdata;
this.childlist = childlist;
this.context = context;
}
@Override
public int getGroupCount() {
return groupdata.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return childlist.get(groupPosition).size();
}
@Override
public Object getGroup(int groupPosition) {
return groupdata.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return childlist.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) {
final GroupViewHolder holder;
if (convertView == null) {
convertView = View.inflate(context, R.layout.groupitem, null);
holder = new GroupViewHolder();
holder.tv_group = (TextView) convertView.findViewById(R.id.tv_group);
holder.group_cb = (CheckBox) convertView.findViewById(R.id.gx_group);
convertView.setTag(holder);
} else {
holder = (GroupViewHolder) convertView.getTag();
}
final GoodsBean.DataBean dataBean = groupdata.get(groupPosition);
String sellerName = dataBean.getSellerName();
holder.group_cb.setChecked(dataBean.isCheck());
holder.tv_group.setText(sellerName);
//点击一级checkbox的状态
holder.group_cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dataBean.setCheck(holder.group_cb.isChecked());
//改变所有孩子的状态
changeChildState(groupPosition,holder.group_cb.isChecked());
EventBus.getDefault().post(jS());
//通过判断一级的checkbox判断全选的状态
changeMianQXstatus(checkGroupAll());
notifyDataSetChanged();
}
});
return convertView;
}
/**
*子条目
*/
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final ChildViewHolder holder;
if (convertView == null) {
convertView = View.inflate(context, R.layout.childitem, null);
holder = new ChildViewHolder();
holder.tv_title= (TextView) convertView.findViewById(R.id.title3);
holder.price= (TextView) convertView.findViewById(R.id.price); //价格
holder.child_cb= (CheckBox) convertView.findViewById(R.id.gouxuan_child); //子勾选
holder.buttonselete= (Button) convertView.findViewById(R.id.buttonselete); //子删除
holder.title_img= (ImageView) convertView.findViewById(R.id.title_img);
holder.yanse= (TextView) convertView.findViewById(R.id.yanse);
convertView.setTag(holder);
} else {
holder = (ChildViewHolder) convertView.getTag();
}
//获取二级list中的对象
final GoodsBean.DataBean.ListBean listBean = childlist.get(groupPosition).get(childPosition);
//取出里面的价格
int price = (int) listBean.getPrice();
holder.child_cb.setChecked(listBean.isCheck());
holder.price.setText("¥:"+price+"");
//标题
String title = listBean.getTitle();
holder.tv_title.setText(title);
//说明
String subhead = listBean.getSubhead();
String substring = subhead.substring(1, 10)+".....";
holder.yanse.setText(substring);
//图片的路径
String images = listBean.getImages();
String[] split = images.split("\\|");
String s = split[0];
//图片加载
ImageLoader.getInstance().displayImage(s, (ImageView) holder.title_img);
//给子条目的checkBox点击事件
holder.child_cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listBean.setCheck(holder.child_cb.isChecked());
EventBus.getDefault().post(jS());
//如果二级的checkBox选中,就让一级的checkBox勾选
if(holder.child_cb.isChecked()) {
if (ischeckAllchild(groupPosition)) {
//改变一级checkBox的状态
changeGroupstatus(groupPosition,true);
//通过判断一级的CheckBox的状态来改变全选的状态
changeMianQXstatus(checkGroupAll());
}
}else{
changeGroupstatus(groupPosition,false);
changeMianQXstatus(checkGroupAll());
}
notifyDataSetChanged();
}
});
// //给子条目的buttonselete点击删除事件
// holder.buttonselete.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// /**
// * 点击条目删除
// */
// AlertDialog.Builder builder = new AlertDialog.Builder(context);
// builder.setIcon(R.mipmap.ic_launcher);
// builder.setTitle("我是对话框");
// builder.setMessage("我是对话框的内容");
// builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// Toast.makeText(context, "点击了取消按钮", Toast.LENGTH_SHORT).show();
// dialog.dismiss();
// }
// });
// builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// Toast.makeText(context, "点击了确定的按钮", Toast.LENGTH_SHORT).show();
// dialog.dismiss();
// //移除数据
// childlist.remove(childPosition);
// //条目刷新
// notifyDataSetChanged();
// }
// });
// AlertDialog dialog = builder.create();
// dialog.show();
// }
// });
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
class GroupViewHolder {
CheckBox group_cb;
TextView tv_group;
}
class ChildViewHolder {
CheckBox child_cb;
TextView tv_title,price,yanse;
ImageView title_img;
Button buttonselete;
}
/**
* 判断全部的二级是CheckBox否选中
*/
private boolean ischeckAllchild(int g){
List<GoodsBean.DataBean.ListBean> listBeen = childlist.get(g);
for (int i = 0; i <listBeen.size() ; i++) {
GoodsBean.DataBean.ListBean listBean = listBeen.get(i);
if(!listBean.isCheck()){
return false;
}
}
return true;
}
/**
* 计算数量和价格
* 通过遍历一级的得到二级的CheckBox,如果是选择的选中状态的话,就统计它们的总计的数量和价格
*/
private CountPrice jS(){
int cou=0;
int jiage=0;
for (int i = 0; i <groupdata.size() ; i++) {
for (int j = 0; j <childlist.get(i).size() ; j++) {
GoodsBean.DataBean.ListBean listBean = childlist.get(i).get(j);
if(listBean.isCheck()){
cou+=listBean.getNum();
jiage+=(int)listBean.getPrice()*listBean.getNum();
}
}
}
CountPrice countAndPrice = new CountPrice();
countAndPrice.setCount(cou);
countAndPrice.setPrice(jiage);
return countAndPrice;
}
/**
* 改变一级列表的状态
*/
private void changeGroupstatus(int groupPosition,boolean flag ){
GoodsBean.DataBean dataBean = groupdata.get(groupPosition);
dataBean.setCheck(flag);
}
/**
* 改变全选的状态
*
*/
private void changeMianQXstatus(boolean flag){
MessageEvent messageEvent = new MessageEvent();
messageEvent.setCheck(flag);
EventBus.getDefault().post(messageEvent);
}
/**
* 判断一级的是否全部选中
*/
private boolean checkGroupAll(){
for (int i = 0; i < groupdata.size(); i++) {
GoodsBean.DataBean dataBean = groupdata.get(i);
if(!dataBean.isCheck()){
return false;
}
}
return true;
}
/**
* 改变所有二级的状态
*/
private void changeChildState(int grouPistion,boolean flag){
List<GoodsBean.DataBean.ListBean> listBeen = childlist.get(grouPistion);
for (int i = 0; i < listBeen.size(); i++) {
listBeen.get(i).setCheck(flag);
}
}
/**
* 改变全选的
*/
public void qx(boolean flag){
for (int i = 0; i < groupdata.size(); i++) {
changeGroupstatus(i, flag);
changeChildState(i, flag);
}
EventBus.getDefault().post(jS());
notifyDataSetChanged();
}
}
//groupitem
// <?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/gx_group"
// android:focusable="false"
// android:layout_width="wrap_content"
// android:layout_height="wrap_content" />
//<TextView
// android:id="@+id/tv_group"
// android:layout_width="wrap_content"
// android:layout_height="wrap_content" />
//</LinearLayout>
//childitem
// <?xml version="1.0" encoding="utf-8"?>
//<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
// android:orientation="vertical" android:layout_width="match_parent"
// android:layout_height="match_parent">
//<TextView
// android:id="@+id/title3"
// android:layout_marginLeft="20dp"
// android:layout_width="match_parent"
// android:layout_height="wrap_content" />
//<LinearLayout
// android:orientation="horizontal"
// android:layout_width="wrap_content"
// android:layout_height="wrap_content">
//<CheckBox
// android:layout_marginLeft="60dp"
// android:gravity="center_vertical"
// android:id="@+id/gouxuan_child"
// android:layout_width="wrap_content"
// android:layout_height="wrap_content" />
//<ImageView
// android:gravity="center_vertical"
// android:id="@+id/title_img"
// android:layout_width="50dp"
// android:layout_height="50dp" />
//
//<TextView
// android:id="@+id/price"
// android:layout_marginLeft="10dp"
// android:layout_width="wrap_content"
// android:layout_height="wrap_content" />
//<TextView
// android:id="@+id/yanse"
// android:layout_marginLeft="10dp"
// android:layout_width="wrap_content"
// android:layout_height="wrap_content" />
//
//</LinearLayout>
//</LinearLayout>
//public class CountPrice {
// private int count;
// private int price;
// public int getCount() {
// return count;
// }
// public void setCount(int count) {
// this.count = count;
// }
// public int getPrice() {
// return price;
// }
// public void setPrice(int price) {
// this.price = price;
// }
//}
//public class MessageEvent {
// private boolean check;
// public boolean isCheck() {
// return check;
// }
// public void setCheck(boolean check) {
// this.check = check;
// }
//}
//三购物车网络操作
public class CartPersenter {
private ICart iCart;
private final CartModel cartModel;
public CartPersenter(ICart iCart){
this.iCart=iCart;
cartModel = new CartModel();
}
/**
* 获取商品的方法
*/
public void getGoods(){
HashMap<String,String> map = new HashMap<>();
map.put("uid","71");
cartModel.getGoods("https://www.zhaoapi.cn/product/getCarts", map, new CGSB<GoodsBean>() {
/**
* 成功的方法
*/
@Override
public void onChengGong(GoodsBean goodsBean) {
List<GoodsBean.DataBean> data = goodsBean.getData();
List< List<GoodsBean.DataBean.ListBean>> childlist=new ArrayList<>();
for (int i = 0; i < data.size(); i++) {
GoodsBean.DataBean dataBean = data.get(i);
List<GoodsBean.DataBean.ListBean> listBeen = dataBean.getList();
childlist.add(listBeen);
}
iCart.ShowData(data,childlist);
}
/**
* 失败的方法
* @param e
*/
@Override
public void onShiBai(IOException e) {
}
});
}
}
//public class CartModel implements Cart{
// private Handler handler=new Handler(Looper.getMainLooper());
//
// @Override
// public void getGoods(String str, Map<String, String> map, final CGSB<GoodsBean> cgsb) {
// HttpUtils.getHttpUtils().doPost(str, map, new Callback() {
// @Override
// public void onFailure(Call call, final IOException e) {
// handler.post(new Runnable() {
// @Override
// public void run() {
// cgsb.onShiBai(e);
// }
// });
// }
//
// @Override
// public void onResponse(Call call, Response response) throws IOException {
// String string = response.body().string();
// final GoodsBean goodsBean = new Gson().fromJson(string, GoodsBean.class);
// handler.post(new Runnable() {
// @Override
// public void run() {
// cgsb.onChengGong(goodsBean);
// }
// });
// }
// });
// }
//}
//public class HttpUtils {
// private static HttpUtils httpUtils;
// private OkHttpClient client;
// private HttpUtils(){
// /**
// * okhttp请求+自定义拦截器
// */
// client = new OkHttpClient.Builder().addInterceptor(new MyInterceptor()).build();
// }
// public static HttpUtils getHttpUtils(){
// if(httpUtils==null){
// synchronized (HttpUtils.class){
// httpUtils=new HttpUtils();
// }
// }
// return httpUtils;
// }
// public void doPost(String str, Map<String,String> map, Callback callback){
// FormBody.Builder builder = new FormBody.Builder();
// for (Map.Entry<String,String> e:map.entrySet()) {
// builder.add(e.getKey(),e.getValue());
// }
// FormBody formBody = builder.build();
// //创建请求,发送请求
// Request request = new Request.Builder().url(str).post(formBody).build();
// client.newCall(request).enqueue(callback);
// }
//}
///**
// * 自定义拦截器
// */
//public class MyInterceptor implements Interceptor {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request ysRequest = chain.request();
// FormBody body = (FormBody) ysRequest.body();
// FormBody.Builder builder = new FormBody.Builder();
// for (int i = 0; i <body.size(); i++) {
// String name = body.name(i);
// String value = body.value(i);
// builder.add(name,value);
// }
// builder.add("source","android");
// FormBody formBody = builder.build();
// Request request = new Request.Builder().url(ysRequest.url()).post(formBody).build();
// return chain.proceed(request);
// }
//}
//public interface Cart {
// public void getGoods(String str, Map<String, String> map, final CGSB<GoodsBean> cgsb);
//}
//public interface CGSB<T> {
// void onChengGong(T t);
// void onShiBai(IOException e);
//}