您的位置:首页 > 理论基础 > 计算机网络

MVP实现购物车(二级列表),删除结算功能,拦截器+封装okHttp

2018-01-13 15:30 796 查看


图片


依赖

compile 'com.squareup.okhttp3:okhttp:3.9.1'
compile 'com.google.code.gson:gson:2.8.+'
compile 'com.github.bumptech.glide:glide:3.6.1'


权限

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


布局

layout_title.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#f00"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="返回"
android:textSize="25sp"
android:padding="10dp"
android:textColor="#fff"
android:id="@+id/btnBack"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textColor="#fff"
android:padding="10dp"
android:text="购物车"
android:layout_weight="1"
android:gravity="center"
/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="编辑"
android:textSize="25sp"
android:padding="10dp"
android:textColor="#fff"
android:id="@+id/btnEditor"/>
</LinearLayout>


layout_bottom.xml

<?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">

<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnCheckAll"
android:text="全选"
android:textSize="25sp"
android:padding="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvAllPrice"
android:textSize="18sp"
android:padding="10dp"
android:textColor="#000"
android:gravity="center"
android:layout_weight="1"
android:text="合计:¥0.00"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="结算(0)"
android:textSize="25sp"
android:textColor="#fff"
android:padding="10dp"
android:background="#f00"
android:id="@+id/btnAmount"
/>
</LinearLayout>


layout_group.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/group_choosed"
android:textSize="25sp"
android:padding="10dp"
android:focusable="false"
android:gravity="center_vertical"
android:text="商家"/>
</LinearLayout>


layout_child.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="wrap_content">

<CheckBox
android:id="@+id/child_choosed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:scaleX="0.6"
android:scaleY="0.6" />
<ImageView
android:id="@+id/img"
android:layout_width="70dp"
android:layout_height="80dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:src="@mipmap/ic_launcher"
android:layout_toRightOf="@id/child_choosed" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:layout_toRightOf="@id/img"
android:orientation="vertical">
<TextView
android:id="@+id/titleName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="酒红色纯红色纯羊毛西服套装"
android:textColor="@android:color/black"
android:textSize="12sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/littleTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:text="属性:粉蓝色"
android:textSize="12sp"
android:textColor="@color/colorPrimary" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:orientation="horizontal">
<TextView
android:id="@+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="¥390"
android:textColor="@android:color/holo_red_dark"
android:textSize="12sp"
android:textStyle="bold" />
<TextView
android:id="@+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="x1"
android:textColor="@android:color/darker_gray" />
<LinearLayout
android:id="@+id/rl_edit"
android:layout_width="120dp"
android:background="@android:color/holo_orange_light"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
>
<TextView
android:id="@+id/btnSub"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:textColor="@android:color/black"
android:background="@android:color/white"
android:layout_margin="1dp"
android:layout_height="match_parent"
android:text=" - " />

<TextView
android:id="@+id/showNum"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:background="@android:color/white"
android:layout_margin="1dp"
android:layout_height="match_parent"
android:text="1"
/>

<TextView
android:id="@+id/btnAdd"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_margin="1dp"
android:background="@android:color/white"
android:layout_height="match_parent"
android:text=" + " />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<Button
android:id="@+id/delete"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:gravity="center"
android:background="@drawable/delete"
android:textSize="20sp"
android:textColor="@android:color/holo_green_dark"
android:layout_margin="5dp"
android:visibility="gone" />

</RelativeLayout>


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"
android:orientation="vertical"
tools:context="com.bwie.shopcar.view.activity.MainActivity">

<include layout="@layout/layout_title"></include>
<ExpandableListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/expandList"
android:layout_weight="1"
>

</ExpandableListView>

<include layout="@layout/layout_bottom"></include>

</LinearLayout>


model包

IShopCarModel

public interface IShopCarModel {

void getCarInfo(String uid, IShopCarPresenter iShopCarPresenter);
}


ShopCarModel

public class ShopCarModel implements IShopCarModel {
private static Handler handler=new Handler();
@Override
public void getCarInfo(String uid, final IShopCarPresenter iShopCarPresenter) {

Map<String,String> params=new HashMap<>();
params.put("uid",uid);
OkHttpUtils okHttpUtils=OkHttpUtils.getInstance();
okHttpUtils.doGet(Constants.GET_CARTS, params, new OnFinishListener() {
@Override
public void onFailed(String msg) {
iShopCarPresenter.onFailed(msg);
}

@Override
public void onSuccess(Object obj) {
//Gson解析
Gson gson=new Gson();
ShopCarBean shopCarBean = gson.fromJson(obj.toString(), ShopCarBean.class);
iShopCarPresenter.onSuccess(shopCarBean.getData());
}
});

}

}


presenter包

IShopCarPresenter

public interface IShopCarPresenter {
void getCarInfo(String uid);
void onSuccess(List<ShopCarBean.DataBean> data);
void onFailed(String msg);
void onDestory();

}


ShopCarPresenter

public class ShopCarPresenter implements IShopCarPresenter {

private IMainView iMainView;
private final ShopCarModel shopCarModel;

public ShopCarPresenter(IMainView iMainView) {
this.iMainView = iMainView;
shopCarModel = new ShopCarModel();
}

@Override
public void getCarInfo(String uid) {
shopCarModel.getCarInfo(uid,this);

}

@Override
public void onSuccess(List<ShopCarBean.DataBean> data) {
if(null!=iMainView){
iMainView.onSuccess(data);
}

}

@Override
public void onFailed(String msg) {
if(null!=iMainView){
iMainView.onFailed(msg);
}
}

@Override
public void onDestory() {
if(null!=iMainView){
iMainView=null;
}

}
}


utils包

Constants

public class Constants {
//请求的服务器主机名
public static final String HOST_NAME="https://www.zhaoapi.cn";
/**
*查询购物车
*/

public static final String GET_CARTS=HOST_NAME+"/product/getCarts";
}


OnFinishListener

public interface OnFinishListener {
void onFailed(String msg);
void onSuccess(Object obj);
}


CommonInterceptor拦截器

public class CommonInterceptor implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
//得到原始的请求对象
Request request = chain.request();

//得到用户所使用的请求方式
String method = request.method();
if("GET".equals(method)){
//原始的请求接口
String oldUrl = request.url().toString();
//拼接一个新的接口
String newUrl = oldUrl + "&source=android";
//重新构建请求体
request =new Request.Builder()
.url(newUrl)
.build();
}else if ("POST".equals(method)) {
//得到原始的url
String oldUrl = request.url().toString();
//得到原有的请求参数
FormBody oldBody = (FormBody) request.body();
//新的构建项
FormBody.Builder builder = new FormBody.Builder();
for (int i = 0; i < oldBody.size(); i++) {
//取出相关请求参数(原有的)
String name = oldBody.name(i);
String value = oldBody.value(i);
//将原始的参数拼装到新的构建体当中
builder.add(name, value);
}
//拼装我们的公共参数
builder.add("source", "android");
request=new Request.Builder()
.url(oldUrl)
.post(builder.build())
.build();

}

//重新发送请求
return chain.proceed(request);
}
}


OkHttpUtils

public class OkHttpUtils {
private static Handler handler=new Handler();
//单例模式
private static OkHttpUtils OK_HTTP_UTILS=null;

/**
* 得到OkHttpUtils实例对象
*
* @return
*/
private OkHttpUtils(){}
public static OkHttpUtils getInstance(){
if(null==OK_HTTP_UTILS){
synchronized (OkHttpUtils.class){
if(null==OK_HTTP_UTILS){
OK_HTTP_UTILS=new OkHttpUtils();
}
}
}
return OK_HTTP_UTILS;
}

/**
* Get请求
* @param onFinishListener
*/

public void doGet(String path, Map<String,String> map,final OnFinishListener onFinishListener){
StringBuffer sb = new StringBuffer();
sb.append(path);
//判断path是否包含一个
if(sb.indexOf("?")!=-1){
//判断"?"是否在最后一个
if(sb.indexOf("?")!=sb.length()-1){
sb.append("&");
}

}else{
sb.append("?");
}
//遍历map集合中所有请求参数
for(Map.Entry<String, String> entry:map.entrySet()){
sb.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
//判断get请求路径最后是否包含一个"&"
if(sb.lastIndexOf("&")!=-1){
sb.deleteCharAt(sb.length()-1);
}

OkHttpClient okHttpClient=new OkHttpClient.Builder()
//添加应用拦截器
.addInterceptor(new CommonInterceptor())
//.addNetworkInterceptor() //添加网络拦截器
.build();
//构建请求项
Request request=new Request.Builder()
.get()
.url(sb.toString())
.build();
Call call =okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
//请求失败
handler.post(new Runnable() {
@Override
public void run() {
onFinishListener.onFailed(e.getMessage());

}
});

}

@Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()){
//得到服务器的响应结果
final String result = response.body().string();
//请求成功
handler.post(new Runnable() {
@Override
public void run() {
//主线程当中执行
onFinishListener.onSuccess(result);
}
});

}
}
});

}
/**
* post请求
*
* @param path
* @param map
* @param onFinishListener
*/

public void doPost(String path,Map<String,String> map,final OnFinishListener onFinishListener){
OkHttpClient okHttpClient=new OkHttpClient.Builder()
//添加应用拦截器 公共参数
.addInterceptor(new CommonInterceptor())
.build();
//构建参数的对象
FormBody.Builder builder = new FormBody.Builder();
//遍历map集合,获取用户的key/value
for(String key:map.keySet()){
builder.add(key,map.get(key));
}
//构建请求项
Request request=new Request.Builder()
.post(builder.build())
.url(path)
.build();
Call call = okHttpClient.newCall(request);

call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
onFinishListener.onFailed(e.getMessage());
}
});
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
final String result = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
onFinishListener.onSuccess(result);
}
});

}
}
});
}

}


示例bean包

ShopCarBean

注:添加在ShopCarBean里面的字段

//商家是否被选中 组条目是否被选中
private boolean isGroupChoosed;

public boolean isGroupChoosed() {
return isGroupChoosed;
}

public void setGroupChoosed(boolean groupChoosed) {
isGroupChoosed = groupChoosed;
}


//子条目商品是否被选中的一个字段状态
private boolean isChildChoosed;

public boolean isChildChoosed() {
return isChildChoosed;
}

public void setChildChoosed(boolean childChoosed) {
isChildChoosed = childChoosed;
}


public class ShopCarBean {

/**
* msg : 请求成功
* code : 0
* data : [{"list":[{"bargainPrice":111.99,"createtime":"2017-10-03T23:53:28","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":8,"price":324,"pscid":1,"selected":0,"sellerid":1,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家1","sellerid":"1"},{"list":[{"bargainPrice":22.9,"createtime":"2017-10-03T23:53:28","detailUrl":"https://item.m.jd.com/product/2542855.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t1930/284/2865629620/390243/e3ade9c4/56f0a08fNbd3a1235.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2137/336/2802996626/155915/e5e90d7a/56f0a09cN33e01bd0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t1882/31/2772215910/389956/c8dbf370/56f0a0a2Na0c86ea6.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2620/166/2703833710/312660/531aa913/57709035N33857877.jpg!q70.jpg","num":1,"pid":26,"price":88,"pscid":2,"selected":0,"sellerid":3,"subhead":"三只松鼠零食特惠,专区满99减50,满199减100,火速抢购》","title":"三只松鼠 坚果炒货 零食奶油味 碧根果225g/袋"}],"sellerName":"商家3","sellerid":"3"},{"list":[{"bargainPrice":1999,"createtime":"2017-10-10T16:09:02","detailUrl":"https://item.m.jd.com/product/5025971.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t7210/232/3738666823/232298/9004583e/59c3a9a7N8de42e15.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8356/82/2107423621/109733/c019b8c6/59c3a9a6Ne9a4bdd7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t10219/74/25356012/171379/7d55e296/59c3a9a8N82fa6e02.jpg!q70.jpg","num":1,"pid":49,"price":333,"pscid":39,"selected":0,"sellerid":5,"subhead":"vivo X20 带你开启全面屏时代!逆光也清晰,照亮你的美!","title":"vivo X20 全面屏手机 全网通 4GB+64GB 金色 移动联通电信4G手机 双卡双待"}],"sellerName":"商家5","sellerid":"5"},{"list":[{"bargainPrice":11800,"createtime":"2017-10-03T23:53:28","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":62,"price":15999,"pscid":40,"selected":0,"sellerid":6,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家6","sellerid":"6"},{"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":20,"price":599,"pscid":1,"selected":0,"sellerid":13,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家13","sellerid":"13"},{"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":5,"price":88.99,"pscid":1,"selected":0,"sellerid":21,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家21","sellerid":"21"}]
*/

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-03T23:53:28","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":8,"price":324,"pscid":1,"selected":0,"sellerid":1,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}]
* sellerName : 商家1
* sellerid : 1
*/

private String sellerName;
private String sellerid;
private List<ListBean> list;

//商家是否被选中 组条目是否被选中
private boolean isGroupChoosed;

public boolean isGroupChoosed() {
return isGroupChoosed;
}

public void setGroupChoosed(boolean groupChoosed) {
isGroupChoosed = groupChoosed;
}

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-03T23:53:28
* detailUrl : https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends * images : https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg * num : 1
* pid : 8
* price : 324.0
* pscid : 1
* selected : 0
* sellerid : 1
* 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;
private int sellerid;
private String subhead;
private String title;

//子条目商品是否被选中的一个字段状态
private boolean isChildChoosed;

public boolean isChildChoosed() {
return isChildChoosed;
}

public void setChildChoosed(boolean childChoosed) {
isChildChoosed = childChoosed;
}

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;
}
}
}
}


view包下activity包

IMainView

public interface IMainView {
void onSuccess(List<ShopCarBean.DataBean> data);
void onFailed(String msg);
}


MainActivity

public class MainActivity extends AppCompatActivity implements IMainView, MyExpandAdapter.ModifyGoodsItemNumberListener, MyExpandAdapter.CheckGroupItemListener {

private TextView tvAllPrice;
private TextView btnAmount;
private TextView btnEditor;
private CheckBox btnCheckAll;
private ExpandableListView expandList;
private ShopCarPresenter shopCarPresenter;
private MyExpandAdapter adapter;
private List<ShopCarBean.DataBean> list;

//购买商品的总数量
private int totalNum = 0;
//购买商品的总价
private double totalPrice= 0.00;

//默认是false
private boolean flag;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//隐藏actionbar
getSupportActionBar().hide();

//查找控件
init();

//获取购物车信息
shopCarPresenter = new ShopCarPresenter(this);
shopCarPresenter.getCarInfo("4861");

//设置适配器
adapter = new MyExpandAdapter(this);
expandList.setAdapter(adapter);
//设置商品加减的监听
adapter.setModifyGoodsItemNumberListener(this);
//设置商家以及商品是否被选中的监听
adapter.setCheckGroupItemListener(this);
//底部复选框的点击事件
btnCheckAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isChoosedAll(((CheckBox)view).isChecked());
//计算总价
checkedPrice();
}
});
//编辑的点击事件
btnEditor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!flag){//编辑 -> 完成
flag=true;
btnEditor.setText("完成");
adapter.showDeleteButton(flag);
}else{
flag=false;
btnEditor.setText("编辑");
adapter.showDeleteButton(flag);
}
}
});

}

private void init() {
//二级列表
expandList = (ExpandableListView) findViewById(R.id.expandList);
//购物车底部栏的全选框
btnCheckAll = (CheckBox) findViewById(R.id.btnCheckAll);
//合计,计算总价
tvAllPrice = (TextView) findViewById(R.id.tvAllPrice);
//结算按钮
btnAmount = (TextView) findViewById(R.id.btnAmount);
//找到编辑控件
btnEditor = (TextView) findViewById(R.id.btnEditor);

}

//默认展开二级列表的方法
private void defaultExpand(){
for(int i=0;i<adapter.getGroupCount();i++){
expandList.expandGroup(i);

}
}

@Override
public void onSuccess(List<ShopCarBean.DataBean> data) {

this.list=data;
adapter.setList(list);

//默认展开二级列表
defaultExpand();

}

@Override
public void onFailed(String msg) {
Toast.makeText(this,msg.toString(),Toast.LENGTH_SHORT).show();
}
//商品加
@Override
public void doIncrease(int groupPosition, int childPosition, View view) {
ShopCarBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition);
//取出当前的商品数量
int currentNum = listBean.getNum();
//商品++
currentNum++;
//将商品数量设置javabean上
listBean.setNum(currentNum);
//刷新适配器
adapter.notifyDataSetChanged();
//计算总价
checkedPrice();

}
//商品减
@Override
public void doDecrease(int groupPosition, int childPosition, View view) {
ShopCarBean.DataBean.ListBean listBean = list.get(groupPosition).getList().get(childPosition);
int currentNum = listBean.getNum();
if(currentNum==1){
return;
}
currentNum--;
listBean.setNum(currentNum);

//刷新适配器
adapter.notifyDataSetChanged();
//计算总价
checkedPrice();

}
//商品删除
@Override
public void deleteItem(int childPosition) {
list.remove(childPosition);

//刷新适配器
adapter.notifyDataSetChanged();
//计算总价
checkedPrice();

}

//商家checkbox
@Override
public void checkGroupItem(int groupPosition, boolean isChecked) {
//商家javabean
ShopCarBean.DataBean dataBean = list.get(groupPosition);
//商家的复选框的选中状态
dataBean.setGroupChoosed(isChecked);

//遍历商家里面的商品,将商品置为同样的状态
for(ShopCarBean.DataBean.ListBean listBean:dataBean.getList()){
listBean.setChildChoosed(isChecked);
}

//将底部全选btnCheckAll置为与上面同样的状态
if(isCheckAll()){
btnCheckAll.setChecked(true);
}else{
btnCheckAll.setChecked(false);
}

//刷新适配器
adapter.notifyDataSetChanged();
//计算总价
checkedPrice();

}

//商品的checkBox

@Override
public void checkChildItem(int groupPosition, int childPosition, boolean isChecked) {
ShopCarBean.DataBean dataBean = list.get(groupPosition);//商家
ShopCarBean.DataBean.ListBean listBean = dataBean.getList().get(childPosition);//商品
//你点击商家的商品条目将其选中状态记录
listBean.setChildChoosed(isChecked);

//检测商家里面的每一个商品是否被选中,如果被选中,返回boolean
boolean result = isGoodsCheckAll(groupPosition);
if(result){
dataBean.setGroupChoosed(result);
}else{
dataBean.setGroupChoosed(result);
}

//底部结算那个checkbox状态(全选)
if(isCheckAll()){
btnCheckAll.setChecked(true);
}else{
btnCheckAll.setChecked(false);
}

//刷新适配器
adapter.notifyDataSetChanged();
//计算总价
checkedPrice();

}

/**
* 检测某个商家的商品是否都选中,如果都选中的话,商家CheckBox应该是选中状态
* @param groupPosition
* @return
*/
private boolean isGoodsCheckAll(int groupPosition){
List<ShopCarBean.DataBean.ListBean> lists = this.list.get(groupPosition).getList();
//遍历某一个商家的每个商品是否被选中
for(ShopCarBean.DataBean.ListBean list:lists){
if(list.isChildChoosed()){//是选中状态
continue;
}else{
return false;
}
}
return true;
}

//购物车商品是否全部选中
private boolean isCheckAll(){
for(ShopCarBean.DataBean dataBean:list){
if(!dataBean.isGroupChoosed()){
return false;
}
}

return true;
}

//全选反选
private void isChoosedAll(boolean isChecked){
for(ShopCarBean.DataBean dataBean:list){
dataBean.setGroupChoosed(isChecked);
for(ShopCarBean.DataBean.ListBean listBean:dataBean.getList()){
listBean.setChildChoosed(isChecked);
}
}
//刷新适配器
adapter.notifyDataSetChanged();
}

/**
* 计算你所选中的商品总价
*/
private void checkedPrice(){
//初始化值
totalNum = 0;
totalPrice = 0.00;
for (ShopCarBean.DataBean dataBean : list){

for (ShopCarBean.DataBean.ListBean listBean : dataBean.getList()){
if(listBean.isChildChoosed()){
totalNum++;

totalPrice += listBean.getNum()*listBean.getPrice();

}
}

}

//设置文本信息 合计、结算的商品数量
tvAllPrice.setText("合计:¥"+totalPrice);
btnAmount.setText("结算("+totalNum+")");

}
//解绑
@Override
protected void onDestroy() {
super.onDestroy();
shopCarPresenter.onDestory();
}
}


view包下adapter包

MyExpandAdapter

public class MyExpandAdapter extends BaseExpandableListAdapter{

private List<ShopCarBean.DataBean> data;
private Context context;
//商品加减的一个接口变量
private ModifyGoodsItemNumberListener modifyGoodsItemNumberListener;
//商家商品是否被选中
private CheckGroupItemListener checkGroupItemListener;

//接收是否处于编辑状态的一个boolean值
private boolean isEditor;

public MyExpandAdapter(Context context) {
this.context = context;
}

public void setList(List<ShopCarBean.DataBean> data){
this.data=data;
notifyDataSetChanged();
}

//设置商品的加减监听

public void setModifyGoodsItemNumberListener(ModifyGoodsItemNumberListener modifyGoodsItemNumberListener) {
this.modifyGoodsItemNumberListener = modifyGoodsItemNumberListener;
}
//设置商店商品checkBox选中监听

public void setCheckGroupItemListener(CheckGroupItemListener checkGroupItemListener) {
this.checkGroupItemListener = checkGroupItemListener;
}

//是否显示删除按钮
public void showDeleteButton(boolean isEditor){
this.isEditor=isEditor;
//刷新适配器
notifyDataSetChanged();
}

@Override
public int getGroupCount() {
return data!=null?data.size():0;
}

@Override
public int getChildrenCount(int i) {
return data!=null&&data.get(i).getList()!=null?data.get(i).getList().size():0;
}

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

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

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

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

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

@Override
public View getGroupView(final int groupPosition, boolean b, View view, ViewGroup parent) {
if(view==null){
view = LayoutInflater.from(context).inflate(R.layout.layout_group, parent, false);
}
CheckBox group_choosed = view.findViewById(R.id.group_choosed);
group_choosed.setText(data.get(groupPosition).getSellerName());
//判断商家的复选框的选中状态
if(data.get(groupPosition).isGroupChoosed()){
group_choosed.setChecked(true);
}else{
group_choosed.setChecked(false);
}
//设置商家复选框的点击事件
group_choosed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkGroupItemListener.checkGroupItem(groupPosition,((CheckBox)view).isChecked());
}
});

return view;
}

@Override
public View getChildView(final int groupPosition, final int childPosition, boolean b, View view, ViewGroup parent) {
if(view==null){
view = LayoutInflater.from(context).inflate(R.layout.layout_child, parent, false);

}
//商品选择
final CheckBox child_choosed = view.findViewById(R.id.child_choosed);
//商品图片
ImageView img = view.findViewById(R.id.img);
//商品主标题
TextView titleName = view.findViewById(R.id.titleName);
//商品副标题
TextView littleTitle = view.findViewById(R.id.littleTitle);
//商品价格
TextView price = view.findViewById(R.id.price);
//商品数量
TextView count = view.findViewById(R.id.count);
//商品减
TextView btnSub = view.findViewById(R.id.btnSub);
//商品加减中的数量变化
final TextView showNum = view.findViewById(R.id.showNum);
//商品加
TextView btnAdd = view.findViewById(R.id.btnAdd);
//删除按钮
Button delete = view.findViewById(R.id.delete);

//设置文本信息
titleName.setText(data.get(groupPosition).getList().get(childPosition).getTitle());
littleTitle.setText(data.get(groupPosition).getList().get(childPosition).getSubhead());
price.setText("¥"+data.get(groupPosition).getList().get(childPosition).getPrice());
count.setText("x"+data.get(groupPosition).getList().get(childPosition).getNum());
showNum.setText(data.get(groupPosition).getList().get(childPosition).getNum()+"");
//分割图片
String images = data.get(groupPosition).getList().get(childPosition).getImages();
String[] urls = images.split("\\|");

//加载图片
Glide.with(context).load(urls[0]).into(img);

//商品加
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
modifyGoodsItemNumberListener.doIncrease(groupPosition,childPosition,showNum);
}
});

//商品减
btnSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
modifyGoodsItemNumberListener.doDecrease(groupPosition,childPosition,showNum);
}
});

//商品删除
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
modifyGoodsItemNumberListener.deleteItem(childPosition);
}
});

//设置商品复选框的点击事件

child_choosed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkGroupItemListener.checkChildItem(groupPosition,childPosition,((CheckBox)view).isChecked());
}
});

// 判断商品的复选框的选中状态

if(data.get(groupPosition).getList().get(childPosition).isChildChoosed()){
child_choosed.setChecked(true);
}else{
child_choosed.setChecked(false);
}
//控制删除按钮的隐藏与显示
if(isEditor){
delete.setVisibility(View.VISIBLE);
}else{
delete.setVisibility(View.GONE);
}

return view;
}

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

/**
*商家的复选框以及商品的复选框是否被选中的接口
* 商家复选框以及商品复选框是否被选中接口
*/
public interface  CheckGroupItemListener{
//商家的条目的复选框监听
void checkGroupItem(int groupPosition,boolean isChecked);
//商品的
void checkChildItem(int groupPosition,int childPosition,boolean isChecked);
}

/**
* 商品加减接口
*/
public interface ModifyGoodsItemNumberListener{
void doIncrease(int groupPosition,int childPosition,View view);
void doDecrease(int groupPosition,int childPosition,View view);
void deleteItem(int childPosition);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐