利用MVP+OkHttp可以比较简单地做出这个购物车
不过呢,在做项目的时候往往需要应用程序内各组件间、组件与后台线程间的通信。比如耗时操作,等耗时操作完成后通过Handler或Broadcast将结果通知给UI,N个Activity之间需要通过Listener通信,其实这些都可以通过EventBus轻松实现.
EventBus是一款针对Android优化的发布/订阅事件总线。简化了应用程序内各组件间、组件与后台线程间的通信。优点是开销小,代码更优雅,以及将发送者和接收者解耦。如果Activity和Activity进行交互还好说,如果Fragment和Fragment进行交互着实令人头疼,我们会使用广播来处理,但是使用广播稍显麻烦并且效率也不高,如果传递的数据是实体类需要序列化,那么很显然成本会有点高。
不过,这次没有使用EventBus,给你们推荐链接去具体学习吧,
github地址:https://github.com/greenrobot/EventBus
官方文档:http://greenrobot.org/eventbus/documentation
compile ‘org.greenrobot:eventbus:3.0.0’
EventBus主要角色:
- Event 传递的事件对象
- Subscriber 事件的订阅者
- Publisher 事件的发布者
- ThreadMode 定义函数在何种线程中执行
全选功能暂未实现,还有bug
MVP嘛,懒就懒吧,上代码
M层
public class CartModel implements ICartModel {
@Override
public void getCartData(String url, final LoadNetListener<CartBean> loadNetListener) {
//获取retrofit对象
Request_Interface request_interface = RetrofitManager.getInstance(url).setCreate(Request_Interface.class);
//封装请求方法
Observable<CartBean> cartDataBean = request_interface.getCartDataBean();
cartDataBean.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<CartBean>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(CartBean cartBean) {
loadNetListener.loadSuccess(cartBean);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
@Override
public void updateCartData(String url, Map<String, String> params, final LoadNetListener<UpdateCartBean> loadNetListener) {
//创建retrofit对象
Request_Interface request_interface = RetrofitManager.getInstance(url).setCreate(Request_Interface.class);
//封装请求方法
Observable<UpdateCartBean> updateCartBeanObservable = request_interface.updateCartData(params);
updateCartBeanObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<UpdateCartBean>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(UpdateCartBean updateCartBean) {
loadNetListener.loadSuccess(updateCartBean);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
//删除购物车
@Override
public void deleteCartData(String url, String pid, final LoadNetListener<UpdateCartBean> loadNetListener) {
//获取retrofit对象
Request_Interface request_interface = RetrofitManager.getInstance(url).setCreate(Request_Interface.class);
//封装请求方法
Observable<UpdateCartBean> updateCartBeanObservable = request_interface.deleteCartData(pid);
//开始请求
updateCartBeanObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<UpdateCartBean>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(UpdateCartBean updateCartBean) {
loadNetListener.loadSuccess(updateCartBean);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
//结算
@Override
public double settleAcount(List<CartBean.DataBean> list) {
double sum = 0;
for (int i = 0; i < list.size(); i++) {
List<CartBean.DataBean.ListBean> childList = list.get(i).getList();
for (int j = 0; j < childList.size(); j++) {
int selected = childList.get(j).getSelected();
int num = childList.get(j).getNum();
double price = childList.get(j).getPrice();
if (selected == 1) {
sum = sum + (num * price);
}
}
}
return sum;
}
}
P层联系层
public class CartPresenter {
private CartModel cartModel;
private CartView cartView;
public CartPresenter(CartView cartView) {
this.cartView = cartView;
this.cartModel = new CartModel();
}
//获取购物车数据
public void getCartBean() {
cartModel.getCartData(Constant.Url, new LoadNetListener<CartBean>() {
@Override
public void loadSuccess(CartBean data) {
cartView.showCartDataBean(data);
}
@Override
public void loadFailed(CartBean data) {
}
});
}
/**
* 显示数量和价钱
*/
public void showCountAndPrice(List<CartBean.DataBean> list) {
double v = cartModel.settleAcount(list);
double round = round(v, 2);
cartView.priceAndNum(round);//将结果展示在页面
}
/**
* 刷新购物车
*/
public void updateCart(HashMap<String, String> params) {
cartModel.updateCartData(Constant.Url, params, new LoadNetListener<UpdateCartBean>() {
@Override
public void loadSuccess(UpdateCartBean data) {
cartView.updateCartData();
}
@Override
public void loadFailed(UpdateCartBean data) {
}
});
}
/**
* 删除购物车
*/
public void deleteCart(String pid, final List<CartBean.DataBean.ListBean> childList) {
cartModel.deleteCartData(Constant.Url, pid, new LoadNetListener<UpdateCartBean>() {
@Override
public void loadSuccess(UpdateCartBean data) {
cartView.updateCartData();
}
@Override
public void loadFailed(UpdateCartBean data) {
}
});
}
//精准到小数两位
public static double round(double v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
大V
void showCartDataBean(CartBean cartBean);//显示购物车数据
void priceAndNum(double round);//结算
void updateCartData();
好了,就差适配器了
写这个的时候老烦了,烦的不要不要的,各种引用各种调
public class CartAdapter extends BaseExpandableListAdapter {
private List<CartBean.DataBean> list;
private Context context;
private CartPresenter cartPresenter;
public CartAdapter(List<CartBean.DataBean> list, Context context, CartView cartView) {
this.list = list;
this.context = context;
this.cartPresenter = new CartPresenter(cartView);
}
@Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
final GroupViewHolder groupViewHolder;
if (convertView == null) {
groupViewHolder = new GroupViewHolder();
convertView = View.inflate(context, R.layout.group_item, null);
groupViewHolder.checkmerchant = convertView.findViewById(R.id.checkmerchant);
groupViewHolder.merchantname = convertView.findViewById(R.id.merchantname);
convertView.setTag(groupViewHolder);
} else {
groupViewHolder = (GroupViewHolder) convertView.getTag();
}
final CartBean.DataBean dataBean = list.get(groupPosition);//获取商家数据
groupViewHolder.merchantname.setText(dataBean.getSellerName() + "");//给商家赋值
cartPresenter.showCountAndPrice(list);//结算选中商品
groupViewHolder.checkmerchant.setChecked(dataBean.isGrooup_flag());//设置父列表状态
boolean checkAllChildGoods = isCheckAllChildGoods(list.get(groupPosition).getList());//判断商家下的商品是否被选中
groupViewHolder.checkmerchant.setChecked(checkAllChildGoods);//根据判断结果给商家设置状态
//点击事件
groupViewHolder.checkmerchant.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<CartBean.DataBean.ListBean> childList = CartAdapter.this.list.get(groupPosition).getList();
boolean checked = groupViewHolder.checkmerchant.isChecked();//获取按钮点击事件
dataBean.setGrooup_flag(checked);//给bean类赋值
changeMerchantGoods(checked, groupPosition);//全选反选
cartPresenter.showCountAndPrice(list);//结算
}
});
return convertView;
}
/**
* 全选和反选商家下的商品
*/
private void changeMerchantGoods(boolean checked, int groupPosition) {
//获取当前商家下的商品数据
List<CartBean.DataBean.ListBean> childList = list.get(groupPosition).getList();
for (int i = 0; i < childList.size(); i++) {
childList.get(i).setChild_flag(checked);
if (checked == false) {
childList.get(i).setSelected(0);
} else if (checked == true) {
childList.get(i).setSelected(1);
}
HashMap<String, String> map = new HashMap<>();//获取商品参数
map.put("uid", "71");
map.put("sellerid", "" + childList.get(i).getSellerid());
map.put("pid", "" + childList.get(i).getPid());
map.put("selected", "" + childList.get(i).getSelected());
map.put("num", "" + childList.get(i).getNum());
cartPresenter.updateCart(map);
}
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final ChildViewHolder childViewHolder;
if (convertView == null) {
childViewHolder = new ChildViewHolder();
convertView = View.inflate(context, R.layout.child_item, null);
childViewHolder.goods_checkbox = convertView.findViewById(R.id.goods_checkbox);
childViewHolder.goods_iamge = convertView.findViewById(R.id.goods_iamge);
childViewHolder.goods_title = convertView.findViewById(R.id.goods_title);
childViewHolder.goods_price = convertView.findViewById(R.id.goods_price);
childViewHolder.delete = convertView.findViewById(R.id.delete);
childViewHolder.add_down = convertView.findViewById(R.id.add_down);
convertView.setTag(childViewHolder);
} else {
childViewHolder = (ChildViewHolder) convertView.getTag();
}
Button decrease = childViewHolder.add_down.findViewById(R.id.btnDecrease);
Button increase = childViewHolder.add_down.findViewById(R.id.btnIncrease);
EditText etAmount = childViewHolder.add_down.findViewById(R.id.etAmount);
cartPresenter.showCountAndPrice(list);//结算
//获取商品数据
final CartBean.DataBean.ListBean goodsBean = list.get(groupPosition).getList().get(childPosition);
//赋值
childViewHolder.goods_title.setText(goodsBean.getTitle() + "");
childViewHolder.goods_price.setText("¥" + goodsBean.getPrice() + "");
Glide.with(context).load(list.get(groupPosition).getList().get(childPosition).getImages().split("[|]")[0]).into(childViewHolder.goods_iamge);
//根据selected值改变商品复选框状态
switch (goodsBean.getSelected()) {
case 0:
childViewHolder.goods_checkbox.setChecked(false);
goodsBean.setChild_flag(false);
break;
case 1:
childViewHolder.goods_checkbox.setChecked(true);
goodsBean.setChild_flag(true);
break;
}
//商品点击事件
childViewHolder.goods_checkbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean checked = childViewHolder.goods_checkbox.isChecked();//获取CheckBox的点击状态
goodsBean.setChild_flag(checked);
if (checked == true) {
goodsBean.setSelected(1);
} else {
goodsBean.setSelected(0);
}
HashMap<String, String> map = new HashMap<>();//获取商品参数
//获取购物车的参数
map.put("uid", "71");
map.put("sellerid", "" + goodsBean.getSellerid());
map.put("pid", "" + goodsBean.getPid());
map.put("selected", "" + goodsBean.getSelected());
map.put("num", "" + goodsBean.getNum());
cartPresenter.updateCart(map);//刷新购物车
map.clear();
cartPresenter.showCountAndPrice(list);//结算
notifyDataSetChanged();
}
});
//删除购物车
childViewHolder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cartPresenter.deleteCart(goodsBean.getPid() + "", list.get(groupPosition).getList());//删除购物车
list.get(groupPosition).getList().remove(childPosition);//删除bean类数据
List<CartBean.DataBean.ListBean> childList = CartAdapter.this.list.get(groupPosition).getList();
if (childList == null || childList.isEmpty()) {
list.remove(groupPosition);
}
cartPresenter.showCountAndPrice(list);//结算
notifyDataSetChanged();
}
});
etAmount.setText(goodsBean.getNum() + "");//给加减器数量赋值
decrease.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num = goodsBean.getNum();
if (num == 1) {
goodsBean.setNum(1);
} else {
num--;
goodsBean.setNum(num);
}
HashMap<String, String> map = new HashMap<>();//获取商品参数
//获取购物车的参数
map.put("uid", "71");
map.put("sellerid", "" + goodsBean.getSellerid());
map.put("pid", "" + goodsBean.getPid());
map.put("selected", "" + goodsBean.getSelected());
map.put("num", "" + goodsBean.getNum());
cartPresenter.updateCart(map);//刷新购物车
map.clear();
cartPresenter.showCountAndPrice(list);//结算
}
});
increase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num = goodsBean.getNum();
if (num < 1) {
goodsBean.setNum(1);
} else {
num++;
goodsBean.setNum(num);
}
HashMap<String, String> map = new HashMap<>();//获取商品参数
//获取购物车的参数
map.put("uid", "71");
map.put("sellerid", "" + goodsBean.getSellerid());
map.put("pid", "" + goodsBean.getPid());
map.put("selected", "" + goodsBean.getSelected());
map.put("num", "" + goodsBean.getNum());
cartPresenter.updateCart(map);//刷新购物车
map.clear();
cartPresenter.showCountAndPrice(list);//结算
}
});
return convertView;
}
/**
* 判断是否选中当前商家下的商品
*/
private boolean isCheckAllChildGoods(List<CartBean.DataBean.ListBean> childList) {
//遍历字列表,判断是否全选所有的子列表的商品
for (int i = 0; i < childList.size(); i++) {
int selected = childList.get(i).getSelected();
if (selected == 0) {
return false;
}
}
return true;
}
/**
* 全选和反选所有的商品
*/
public void checkAllGoods(boolean checked) {
for (int i = 0; i < list.size(); i++) {
list.get(i).setGrooup_flag(checked);//商家设置状态值
List<CartBean.DataBean.ListBean> childList = list.get(i).getList();//商家集合
for (int j = 0; j < childList.size(); j++) {
if (checked == true) {
childList.get(j).setSelected(1);
childList.get(j).setChild_flag(true);
} else {
childList.get(j).setSelected(0);
childList.get(j).setChild_flag(false);
}
HashMap<String, String> map = new HashMap<>();//获取商品参数
//获取购物车的参数
map.put("uid", "71");
map.put("sellerid", "" + childList.get(j).getSellerid());
map.put("pid", "" + childList.get(j).getPid());
map.put("selected", "" + childList.get(j).getSelected());
map.put("num", "" + childList.get(j).getNum());
cartPresenter.updateCart(map);//刷新购物车
}
}
}
class GroupViewHolder {
CheckBox checkmerchant;
TextView merchantname;
}
class ChildViewHolder {
CheckBox goods_checkbox;
TextView goods_title;
TextView goods_price;
ImageView goods_iamge;
Button delete;
AmountView add_down;
}
}
activity层
@Override
public void showCartDataBean(CartBean cartBean) {
final List<CartBean.DataBean> data = cartBean.getData();
cartAdapter = new CartAdapter(data, getActivity(), this);
mCart.setAdapter(cartAdapter);
int groupCount = cartAdapter.getGroupCount();
for (int i = 0; i < groupCount; i++) {
mCart.expandGroup(i);
}
//全选和反选所有商品
mCheckallgoods.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*cartAdapter.checkAllGoods(mCheckallgoods.isChecked());*/
boolean checked = mCheckallgoods.isChecked();
for (int i = 0; i < data.size(); i++) {
List<CartBean.DataBean.ListBean> childList = data.get(i).getList();
for (int j = 0; j < childList.size(); j++) {
CartBean.DataBean.ListBean listBean = childList.get(j);
listBean.setChild_flag(checked);
if (checked == true) {
childList.get(j).setSelected(1);
childList.get(j).setChild_flag(true);
} else {
childList.get(j).setSelected(0);
childList.get(j).setChild_flag(false);
}
HashMap<String, String> map = new HashMap<>();//获取商品参数
//获取购物车的参数
map.put("uid", "71");
map.put("sellerid", "" + childList.get(j).getSellerid());
map.put("pid", "" + childList.get(j).getPid());
map.put("selected", "" + childList.get(j).getSelected());
map.put("num", "" + childList.get(j).getNum());
cartPresenter.updateCart(map);//刷新购物车
}
}
}
});
}
@Override
public void priceAndNum(double round) {
mSumcount.setText("合计: " + round + " ");
}
//更新购物车
@Override
public void updateCartData() {
cartAdapter.notifyDataSetChanged();
}