您的位置:首页 > 其它

电商项目之简单购物车

2018-01-07 20:35 507 查看
效果图:






项目要求:

1.项目框架:MVP,图片加载用Fresco,网络请求用OKhttp+Retrofit实现(自己封装,加单例模式),

2.完成购物车数据添加(如果接口无数据,可用接口工具添加数据),

3.自定义view实现加减按钮,每次点击加减,item中的总数及总价要做出相应的改变。

4.当数量为1时,点击减号,数量不变,吐司提示用户最小数量为1。

5.底部总数及总价为所有item项中的总价及总数,每个item中数量价格的更改,底部总价总数要与之联动

6.实现单选反选全选功能,首次进入默认全选,item未选中时总数及总价不计入底部数据,改变选中状态时,底部总数及总价能做出正确修改

7.点击删除按钮,删除item,底部总数及总价能做出正确修改,接口数据删除。

接口如下:

添加购物车

接口地址:http://120.27.23.105/product/addCart

返回格式:json

请求方式:get/post

接口备注:添加购物车(删除sellerid字段)

请求参数说明:

名称类型
必填 说明

uid string 是
用户id

pid string 是
商品id

 

查询购物车

接口地址:http://120.27.23.105/product/getCarts

返回格式:json

请求方式:get/post

接口备注:查询购物车

请求参数说明:

名称类型
必填 说明

uid string 是
用户id

 

更新购物车

接口地址:http://120.27.23.105/product/updateCarts?uid=71&sellerid=1&pid=1&selected=0&num=10

返回格式:json

请求方式:get/post

接口备注:更新购物车

请求参数说明:

名称类型
必填 说明

uid string 是
用户id

sellerid string 是商户id

pid string 是
商品id

num string 是
商品数量

selected string 是是否选中

 

删除购物车

接口地址:http://120.27.23.105/product/deleteCart?uid=72&pid=1

返回格式:json

请求方式:get/post

接口备注:删除购物车

请求参数说明:

名称类型
必填 说明

uid string 是
用户id

pid string 是
商品id


本项目所需依赖:

   //retrofit

   
compile 'com.squareup.retrofit2:retrofit:+'

    compile 'com.squareup.retrofit2:converter-gson:+'

    //Rxjava2

   
compile 'io.reactivex.rxjava2:rxjava:+'

    compile 'io.reactivex.rxjava2:rxandroid:+'

    //让retrofit支持Rxjava2

   
compile 'com.squareup.retrofit2:adapter-rxjava2:+'

    //butterknife

   
compile 'com.jakewharton:butterknife:8.8.1'

    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

    //fresco

   
compile 'com.facebook.fresco:fresco:+'

    //支持gif

    compile 'com.facebook.fresco:animated-gif:+'

    //eventbus

   
compile 'org.greenrobot:eventbus:3.0.0'



[b]本项目所需权限:[/b]

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



本项目所需素材如下:


                       

       


       


       


       



项目结构如下:

                




代码(由上到下):

adapter:


MessageEvent

package com.bwie.myapplication.adapter;

public class MessageEvent {
private boolean checkd;

public boolean isCheckd() {
return checkd;
}

public void setCheckd(boolean checkd) {
this.checkd = checkd;
}
}


MyCarShowAdapter

package com.bwie.myapplication.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bwie.myapplication.R;
import com.bwie.myapplication.bean.DeleteGoodsBean;
import com.bwie.myapplication.bean.ShoppingcarBean;
import com.bwie.myapplication.bean.UpdateGoodsBean;
import com.bwie.myapplication.presenter.DeleteGoodsPresenter;
import com.bwie.myapplication.presenter.UpdateGoodsPresenter;
import com.bwie.myapplication.view.IDeleteGoodsView;
import com.bwie.myapplication.view.IUpdateGoodsView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

public class MyCarShowAdapter extends BaseExpandableListAdapter implements IDeleteGoodsView, IUpdateGoodsView {
private Context context;
private List<ShoppingcarBean.DataBean> data;
private List<List<ShoppingcarBean.DataBean.ListBean>> list;
private DeleteGoodsPresenter deleteGoodsPresenter;
private boolean isVisible;
private SharedPreferences myself;
private String uid;
private UpdateGoodsPresenter updateGoodsPresenter;

public MyCarShowAdapter(Context context, List<ShoppingcarBean.DataBean> data, List<List<ShoppingcarBean.DataBean.ListBean>> list) {
this.context = context;
this.data = data;
this.list = list;
}

@Override
public int getGroupCount() {
return data.size();
}

@Override
public int getChildrenCount(int groupPosition) {
return list.get(groupPosition).size();
}

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

@Override
public Object getChild(int groupPosition, int childPosition) {
return list.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 ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = View.inflate(context, R.layout.group1, null);
holder.textView = (TextView) convertView.findViewById(R.id.g_title);
holder.che = (CheckBox) convertView.findViewById(R.id.che);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(data.get(groupPosition).getSellerName());
//设置一级列表checkBox的状态
holder.che.setChecked(data.get(groupPosition).isChecked());
//一级列表checkBox的点击事件
holder.che.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//判断一级列表复选框的状态  设置为true或false
data.get(groupPosition).setChecked(holder.che.isChecked());
//改变二级checkbod的状态
changeChildCbState(groupPosition, holder.che.isChecked());
//算钱
EventBus.getDefault().post(computer());
//改变全选状态   isAllGroupCbSelect判断一级是否全部选中
changeAllCbState(isAllGroupCbSelect());
//必刷新
notifyDataSetChanged();
}
});
return convertView;
}

//二级标题
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
Fresco.initialize(context);
final ShoppingcarBean.DataBean.ListBean listBean = list.get(groupPosition).get(childPosition);
final ViewHolder2 holder2;
if (convertView == null) {
holder2 = new ViewHolder2();
convertView = View.inflate(context, R.layout.chidren, null);
holder2.z_title = (TextView) convertView.findViewById(R.id.z_title);
holder2.z_che = (CheckBox) convertView.findViewById(R.id.z_che);
holder2.img = (SimpleDraweeView) convertView.findViewById(R.id.z_img);
holder2.price = (TextView) convertView.findViewById(R.id.z_price);
holder2.xiangqing = (TextView) convertView.findViewById(R.id.z_shuxing);
holder2.jian = (ImageView) convertView.findViewById(R.id.iv_jian);
holder2.jia = (ImageView) convertView.findViewById(R.id.iv_add);
holder2.del = (ImageView) convertView.findViewById(R.id.del);
holder2.num = (TextView) convertView.findViewById(R.id.tv_num);
convertView.setTag(holder2);

} else {
holder2 = (ViewHolder2) convertView.getTag();
}
holder2.num.setText(list.get(groupPosition).get(childPosition).getNum() + "");
holder2.z_title.setText(list.get(groupPosition).get(childPosition).getTitle());
holder2.price.setText("¥" + list.get(groupPosition).get(childPosition).getBargainPrice());
holder2.xiangqing.setText(list.get(groupPosition).get(childPosition).getSubhead());
String images = list.get(groupPosition).get(childPosition).getImages();
String[] split = images.split("\\|");
//   ImageLoader.getInstance().displayImage(split[0], holder2.img);
Uri parse = Uri.parse(split[0]);
holder2.img.setImageURI(parse);
//判断是否需要显示删除按钮
if (!isVisible) {
//隐藏
holder2.del.setVisibility(View.GONE);
} else {
holder2.del.setVisibility(View.VISIBLE);
}

//设置二级列表checkbox的属性
holder2.z_che.setChecked(list.get(groupPosition).get(childPosition).isChecked());
//二级列表的点击事件
holder2.z_che.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//设置该条目中的checkbox属性值
listBean.setChecked(holder2.z_che.isChecked());
//计算价钱
PriceAndCountEvent priceAndCountEvent = computer();
EventBus.getDefault().post(priceAndCountEvent);
//判断当前checkbox是选中的状态
if (holder2.z_che.isChecked()) {
//如果全部选中(isAllChildCbSelected)
if (isAllChildCbSelected(groupPosition)) {
//改变一级列表的状态
changeGroupCbState(groupPosition, true);
//改变全选的状态
changeAllCbState(isAllGroupCbSelect());
}
} else {
//如果没有全部选中,一级列表的checkbox为false不为选中
changeGroupCbState(groupPosition, false);
changeAllCbState(isAllGroupCbSelect());
}
notifyDataSetChanged();
}
});
updateGoodsPresenter = new UpdateGoodsPresenter(this);
//加号
holder2.jia.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int num = listBean.getNum();
//num为int类型所以要加空字符串
holder2.num.setText(++num + "");
listBean.setNum(num);
updateGoodsPresenter.updateGoods(listBean.getPid() + "", listBean.getSellerid() + "", listBean.getSelected() + "", num + "");
//如果二级列表的checkbox为选中,计算价钱
13767

if (holder2.z_che.isChecked()) {
PriceAndCountEvent priceAndCountEvent = computer();
EventBus.getDefault().post(priceAndCountEvent);
}
}
});
//减号
holder2.jian.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int num = listBean.getNum();
if (num == 1) {
Toast.makeText(context, "已经不能再减了,", Toast.LENGTH_SHORT).show();
return;
}

holder2.num.setText(--num + "");
listBean.setNum(num);
updateGoodsPresenter.updateGoods(listBean.getPid() + "", listBean.getSellerid() + "", listBean.getSelected() + "", num + "");
if (holder2.z_che.isChecked()) {
PriceAndCountEvent priceAndCountEvent = computer();
EventBus.getDefault().post(priceAndCountEvent);
}
}
});

deleteGoodsPresenter = new DeleteGoodsPresenter(this);
myself = context.getSharedPreferences("myself", Context.MODE_PRIVATE);
uid = myself.getString("uid", null);
//点击删除购物车里面的内容
holder2.del.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (holder2.z_che.isChecked()) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("确认要删除吗?");
builder.setTitle("提示");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteGoodsPresenter.deleteGoods(list.get(groupPosition).get(childPosition).getPid() + "");
Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
List<ShoppingcarBean.DataBean.ListBean> listBeen = list.get(groupPosition);
ShoppingcarBean.DataBean.ListBean remove = listBeen.remove(childPosition);
if (listBeen.size() == 0) {
//先移除二级列表的集合,再移除一级列表的集合
list.remove(groupPosition);
data.remove(groupPosition);
}
//算钱
EventBus.getDefault().post(computer());
notifyDataSetChanged();
dialog.dismiss();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "取消删除", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
builder.create().show();

//点击传值

} else {
Toast.makeText(context, "请选择商品", Toast.LENGTH_SHORT).show();
}

}
});
return convertView;
}

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

@Override
public void onSuccess(DeleteGoodsBean deleteGoodsBean) {

}

@Override
public void onSuccess(UpdateGoodsBean updateGoodsBean) {
Log.e("updateGoodsBean", "OK" + updateGoodsBean.getMsg());
}

@Override
public void onFailed(Throwable throwable) {
Log.e("updateGoodsBean", "No" + throwable.toString());
}

class ViewHolder {
TextView textView;
CheckBox che;
}

class ViewHolder2 {
SimpleDraweeView img;
TextView z_title;
CheckBox z_che;
TextView price;
TextView xiangqing;
ImageView jia;
ImageView jian;
ImageView del;
TextView num;
}

//改变二级列表的checkbox的状态   如果一级选中,控制二级也选中
private void changeChildCbState(int groupPosition, boolean flag) {
List<ShoppingcarBean.DataBean.ListBean> listBeen = list.get(groupPosition);
for (int j = 0; j < listBeen.size(); j++) {
ShoppingcarBean.DataBean.ListBean listBean = listBeen.get(j);
listBean.setChecked(flag);
}
}

//判断一级列表是否全部选中
public boolean isAllGroupCbSelect() {
for (int i = 0; i < list.size(); i++) {
ShoppingcarBean.DataBean dataBean = data.get(i);
if (!dataBean.isChecked()) {
return false;
}
}
return true;
}

//改变全选的状态
private void changeAllCbState(boolean flag) {
MessageEvent messageEvent = new MessageEvent();
messageEvent.setCheckd(flag);
EventBus.getDefault().post(messageEvent);
}

//改变一级列表的checkbox的状态
private void changeGroupCbState(int i, boolean flag) {
ShoppingcarBean.DataBean dataBean = data.get(i);
dataBean.setChecked(flag);
}

//判断二级列表是否全部选中
private boolean isAllChildCbSelected(int i) {
List<ShoppingcarBean.DataBean.ListBean> listBeen = list.get(i);
for (int j = 0; j < listBeen.size(); j++) {
ShoppingcarBean.DataBean.ListBean listBean = listBeen.get(j);
if (!listBean.isChecked()) {
return false;
}
}
return true;
}

//设置全选,反选
public void changeAllListCbState(boolean flag) {
for (int i = 0; i < list.size(); i++) {
changeGroupCbState(i, flag);
changeChildCbState(i, flag);
}
//算钱
EventBus.getDefault().post(computer());
notifyDataSetChanged();
}

//计算列表的价钱
private PriceAndCountEvent computer() {
int count = 0;
double price = 0;
int to = 0;
for (int i = 0; i < list.size(); i++) {
List<ShoppingcarBean.DataBean.ListBean> listBeen = list.get(i);
for (int j = 0; j < listBeen.size(); j++) {
ShoppingcarBean.DataBean.ListBean listBean = listBeen.get(j);
if (listBean.isChecked()) {
price += listBean.getNum() * listBean.getBargainPrice();
count += listBean.getNum();
to += listBean.getNum();
}
}
}
PriceAndCountEvent priceAndCountEvent = new PriceAndCountEvent();
priceAndCountEvent.setCount(count);
priceAndCountEvent.setPrice(price);
priceAndCountEvent.setTo(to);
return priceAndCountEvent;
}

/**
* 是否隐藏删除按钮
*
* @param isVisible
* @return
*/
public void showDelete(boolean isVisible) {
this.isVisible = isVisible;
notifyDataSetChanged();
}
}

PriceAndCountEvent

package com.bwie.myapplication.adapter;

public class PriceAndCountEvent {
private double price;
private int count;
private int to;

public double getPrice() {
return price;
}

public int getCount() {
return count;
}

public int getTo() {
return to;
}

public void setPrice(double price) {
this.price = price;
}

public void setCount(int count) {
this.count = count;
}

public void setTo(int to) {
this.to = to;
}
}


bean:

DeleteGoodsBean

package com.bwie.myapplication.bean;

public class DeleteGoodsBean {

/**
* msg : 删除购物车成功
* code : 0
*/

private String msg;
private String code;

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

ShoppingcarBean

package com.bwie.myapplication.bean;

import java.util.List;

public class ShoppingcarBean {

/**
* msg : 请求成功
* code : 0
* data : [{"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":71,"price":32999,"pscid":40,"selected":0,"sellerid":15,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家15","sellerid":"15"}]
*/

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":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":71,"price":32999,"pscid":40,"selected":0,"sellerid":15,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}]
* sellerName : 商家15
* sellerid : 15
*/

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

public boolean isChecked() {
return checked;
}

public void setChecked(boolean checked) {
this.checked = checked;
}

public String getSellerName() {
return sellerName;
}

public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}

public String getSellerid() {
return sellerid;
}

public void setSellerid(String sellerid) {
this.sellerid = sellerid;
}

public List<ListBean> getList() {
return list;
}

public void setList(List<ListBean> list) {
this.list = list;
}

public static class ListBean {
/**
* bargainPrice : 11800.0
* 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 : 71
* price : 32999.0
* pscid : 40
* selected : 0
* sellerid : 15
* subhead : 购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)
* title : 全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G
*/

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

public boolean isChecked() {
return checked;
}

public void setChecked(boolean checked) {
this.checked = checked;
}

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

UpdateGoodsBean

package com.bwie.myapplication.bean;

public class UpdateGoodsBean {

/**
* msg : success
* code : 0
*/

private String msg;
private String code;

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

model:

MyModel

package com.bwie.myapplication.model;

import com.bwie.myapplication.bean.DeleteGoodsBean;
import com.bwie.myapplication.bean.ShoppingcarBean;
import com.bwie.myapplication.bean.UpdateGoodsBean;
import com.bwie.myapplication.utils.RetiofitUtils;
import com.bwie.myapplication.utils.RetiofitVip;

import io.reactivex.Observable;

public class MyModel {
//查询购物车
public Observable<ShoppingcarBean> shoppingcar() {
RetiofitVip retiofitVip = RetiofitUtils.getInstance().create(RetiofitVip.class);
return retiofitVip.shoppingCar("3381");
}

//删除购物车
public Observable<DeleteGoodsBean> deleteGoods(String pid) {
RetiofitVip retiofitVip = RetiofitUtils.getInstance().create(RetiofitVip.class);
return retiofitVip.deleteGoods("3381", pid);
}

//更新购物车
public Observable<UpdateGoodsBean> updateGoods(String pid, String sellerid, String selected, String num) {
RetiofitVip retiofitVip = RetiofitUtils.getInstance().create(RetiofitVip.class);
return retiofitVip.updateGoods("3381", pid, sellerid, selected, num);
}
}

presenter:

DeleteGoodsPresenter

package com.bwie.myapplication.presenter;

import com.bwie.myapplication.bean.DeleteGoodsBean;
import com.bwie.myapplication.model.MyModel;
import com.bwie.myapplication.view.IDeleteGoodsView;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class DeleteGoodsPresenter extends IPresenter<IDeleteGoodsView> {
private MyModel model;

public DeleteGoodsPresenter(IDeleteGoodsView view) {
super(view);
}

@Override
protected void init() {
model = new MyModel();
}

public void deleteGoods(String pid) {
Observable<DeleteGoodsBean> shoppingcar = model.deleteGoods(pid);
shoppingcar
//需要在子线程中联网
.subscribeOn(Schedulers.io())
//需要在UI线程中更新UI
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<DeleteGoodsBean>() {
@Override
public void accept(DeleteGoodsBean deleteGoodsBean) throws Exception {
view.onSuccess(deleteGoodsBean);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
view.onFailed(throwable);
}
});
}
}

IPresenter

package com.bwie.myapplication.presenter;

import com.bwie.myapplication.view.IView;

public abstract class IPresenter<T extends IView> {
protected T view;

public IPresenter(T view) {
this.view = view;
init();
}

protected abstract void init();
}


ShoppingCarPersenter

package com.bwie.myapplication.presenter;

import com.bwie.myapplication.bean.ShoppingcarBean;
import com.bwie.myapplication.model.MyModel;
import com.bwie.myapplication.view.IShoppingcarView;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ShoppingCarPersenter extends IPresenter<IShoppingcarView> {
private MyModel model;

public ShoppingCarPersenter(IShoppingcarView view) {
super(view);
}

@Override
protected void init() {
model = new MyModel();
}

public void shoppingCar() {
Observable<ShoppingcarBean> shoppingcar = model.shoppingcar();
shoppingcar
//需要在子线程中联网
.subscribeOn(Schedulers.io())
//需要在UI线程中更新UI
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<ShoppingcarBean>() {
@Override
public void accept(ShoppingcarBean shoppingcarBean) throws Exception {
view.onSuccess(shoppingcarBean);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
view.onFailed(throwable);
}
});
}
}

UpdateGoodsPresenter

package com.bwie.myapplication.presenter;

import com.bwie.myapplication.bean.UpdateGoodsBean;
import com.bwie.myapplication.model.MyModel;
import com.bwie.myapplication.view.IUpdateGoodsView;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class UpdateGoodsPresenter extends IPresenter<IUpdateGoodsView> {
private MyModel model;

public UpdateGoodsPresenter(IUpdateGoodsView view) {
super(view);
}

@Override
protected void init() {
model = new MyModel();
}

public void updateGoods(String pid, String sellerid, String selected, String num) {
Observable<UpdateGoodsBean> updateGoodsObservable = model.updateGoods(pid, sellerid, selected, num);
updateGoodsObservable
//需要在子线程中联网
.subscribeOn(Schedulers.io())
//需要在UI线程中更新UI
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<UpdateGoodsBean>() {
@Override
public void accept(UpdateGoodsBean updateGoodsBean) throws Exception {
view.onSuccess(updateGoodsBean);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
view.onFailed(throwable);
}
});
}
}


utils:

Intercept

package com.bwie.myapplication.utils;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class Intercept implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl url = original.url().newBuilder()
.addQueryParameter("source", "android")
.build();
//添加请求头
Request request = original.newBuilder()
.url(url)
.build();
return chain.proceed(request);
}
}


RetiofitUtils

package com.bwie.myapplication.utils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetiofitUtils {
public static final String BASE_URL = "http://120.27.23.105/";
private final Retrofit mRetrofit;

public static class SINGLE_HOLDER {
public static final RetiofitUtils INSTANCE = new RetiofitUtils(BASE_URL);
}

public static RetiofitUtils getInstance() {
return SINGLE_HOLDER.INSTANCE;
}

private RetiofitUtils(String baseUrl) {
mRetrofit = buildRetrofit();
}

private OkHttpClient buildOkHttpClient() {
return new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.addInterceptor(new Intercept())
.build();
}

private Retrofit buildRetrofit() {
return new Retrofit.Builder()
.client(buildOkHttpClient())
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}

public <T> T create(Class<T> tClass) {
return mRetrofit.create(tClass);
}

}


RetiofitVip

package com.bwie.myapplication.utils;

import com.bwie.myapplication.bean.DeleteGoodsBean;
import com.bwie.myapplication.bean.ShoppingcarBean;
import com.bwie.myapplication.bean.UpdateGoodsBean;

import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface RetiofitVip {
//查询购物车接口
@GET("product/getCarts")
Observable<ShoppingcarBean> shoppingCar(@Query("uid") String uid);

//删除购物车
@GET("product/deleteCart")
Observable<DeleteGoodsBean> deleteGoods(@Query("uid") String uid,
@Query("pid") String pid);

//更新购物车
@GET("product/updateCarts")
Observable<UpdateGoodsBean> updateGoods(@Query("uid") String uid,
@Query("pid") String pid,
@Query("sellerid") String sellerid,
@Query("selected") String selected,
@Query("num") String num);
}

view:

IDeleteGoodsView

package com.bwie.myapplication.view;

import com.bwie.myapplication.bean.DeleteGoodsBean;

public interface IDeleteGoodsView extends IView {
void onSuccess(DeleteGoodsBean deleteGoodsBean);

void onFailed(Throwable throwable);
}


IShoppingcarView

package com.bwie.myapplication.view;

import com.bwie.myapplication.bean.ShoppingcarBean;

public interface IShoppingcarView extends IView {
void onSuccess(ShoppingcarBean shoppingcarBean);

void onFailed(Throwable throwable);
}


IUpdateGoodsView

package com.bwie.myapplication.view;

import com.bwie.myapplication.bean.UpdateGoodsBean;

public interface IUpdateGoodsView extends IView {
void onSuccess(UpdateGoodsBean updateGoodsBean);

void onFailed(Throwable throwable);
}


IView

package com.bwie.myapplication.view;

public interface IView {
 
}


MainActivity

package com.bwie.myapplication.view;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bwie.myapplication.R;
import com.bwie.myapplication.adapter.MessageEvent;
import com.bwie.myapplication.adapter.MyCarShowAdapter;
import com.bwie.myapplication.adapter.PriceAndCountEvent;
import com.bwie.myapplication.bean.ShoppingcarBean;
import com.bwie.myapplication.presenter.ShoppingCarPersenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements IShoppingcarView {

@BindView(R.id.btnEditor)
TextView btnEditor;
@BindView(R.id.exlv)
ExpandableListView exlv;
@BindView(R.id.checkbox)
CheckBox checkbox;
@BindView(R.id.price)
TextView prices;
@BindView(R.id.num)
TextView nums;
@BindView(R.id.jiesuan)
Button jiesuan;
private ShoppingCarPersenter shoppingCarPersenter;
private List<ShoppingcarBean.DataBean> grouplist = new ArrayList<>();
private List<List<ShoppingcarBean.DataBean.ListBean>> childlist = new ArrayList<>();
private MyCarShowAdapter myCarShowAdapter;
private boolean flag = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
setContentView(R.layout.shopcar_layout);
ButterKnife.bind(this);
shoppingCarPersenter = new ShoppingCarPersenter(this);
shoppingCarPersenter.shoppingCar();
}

@Override
public void onSuccess(ShoppingcarBean shoppingcarBean) {
List<ShoppingcarBean.DataBean> data = shoppingcarBean.getData();
grouplist.clear();
childlist.clear();
grouplist.addAll(data);

for (int i = 0; i < data.size(); i++) {
List<ShoppingcarBean.DataBean.ListBean> list = data.get(i).getList();
childlist.add(list);
}
myCarShowAdapter = new MyCarShowAdapter(MainActivity.this, grouplist, childlist);
exlv.setAdapter(myCarShowAdapter);
exlv.setGroupIndicator(null);
// 展开
for (int i = 0; i < data.size(); i++) {
exlv.expandGroup(i);
}
myCarShowAdapter.notifyDataSetChanged();

}

@Override
public void onFailed(Throwable throwable) {
Log.e("Shopping", "ON" + throwable.toString());
}

@OnClick({R.id.btnEditor, R.id.checkbox})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.btnEditor:
if (childlist.size() >= 0) {
btnEditor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!flag) {// false 隐藏 true 代表显示
//隐藏
flag = true;
myCarShowAdapter.showDelete(flag);
btnEditor.setText("完成");

} else {
//显示
flag = false;
myCarShowAdapter.showDelete(flag);
btnEditor.setText("编辑");
}
}
});
}
break;
case R.id.checkbox:
if (grouplist.size() <= 0 || childlist.size() <= 0) {
checkbox.setChecked(false);
Toast.makeText(MainActivity.this, "购物车为空", Toast.LENGTH_SHORT).show();
} else {
//设置全选
myCarShowAdapter.changeAllListCbState(checkbox.isChecked());
}
break;
}
}

@Subscribe
public void onMessageEvent(MessageEvent event) {
checkbox.setChecked(event.isCheckd());
}

@Subscribe
public void onMessageEven(PriceAndCountEvent event) {
prices.setText(event.getPrice() + "");
nums.setText("共" + event.getCount() + "件商品");
jiesuan.setText("去结算(" + event.getTo() + ")");
}
}


布局文件结构如下:

           





chidren.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<CheckBox
android:id="@+id/z_che"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="11dp" />

<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_toRightOf="@id/z_che"
android:orientation="vertical">

<TextView
android:id="@+id/z_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="三只松鼠大礼包"
android:textSize="16sp"
android:textStyle="bold" />

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/z_img"
android:layout_width="140dp"
android:layout_height="140dp"
android:src="@mipmap/ic_launcher"
app:fadeDuration="20"
app:failureImage="@drawable/icon_failure"
app:placeholderImage="@drawable/icon_progress_bar" />

<TextView
android:id="@+id/z_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_toEndOf="@+id/z_img"
android:layout_toRightOf="@+id/z_img"
android:text="价钱"
android:textColor="#ff0000" />

<TextView
android:id="@+id/z_shuxing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/z_price"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toEndOf="@+id/z_img"
android:layout_toRightOf="@+id/z_img"
android:text="价钱"
android:textColor="@color/colorPrimary"
android:textSize="14sp" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/z_shuxing"
android:layout_marginLeft="5dp"
android:layout_marginTop="20dp"
android:layout_toRightOf="@id/z_img"
android:orientation="horizontal">

<ImageView
android:id="@+id/iv_jian"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/shopcart_minus_red" />

<TextView
android:id="@+id/tv_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="1"
android:textSize="20sp" />

<ImageView
android:id="@+id/iv_add"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:src="@drawable/shopcart_add_red" />

<ImageView
android:id="@+id/del"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="right"
android:layout_weight="1"
android:src="@drawable/rublish" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>


group1.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="match_parent">

<CheckBox
android:id="@+id/che"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginTop="20dp" />

<TextView
android:id="@+id/g_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:text="------------" />
</LinearLayout>


shopcar_layout.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="match_parent"
android:background="#EBEBEB"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:orientation="horizontal">

<TextView
android:id="@+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="返回"
android:textSize="25sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:gravity="center"
android:padding="10dp"
android:text="购物车"
android:textSize="25sp" />

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

</LinearLayout>

<ExpandableListView
android:id="@+id/exlv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#fff"></ExpandableListView>

<RelativeLayout
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff">

<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true" />

<TextView
android:id="@+id/qx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/checkbox"
android:text="全选" />

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/qx"
android:orientation="horizontal">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="总价:" />

<TextView
android:id="@+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.00"
android:textColor="#ff0000"
android:textSize="16sp" />

<TextView
android:id="@+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:text="共0件商品"
android:textColor="#ff0000" />

</LinearLayout>

<Button
android:id="@+id/jiesuan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#ff0000"
android:text="去结算(0)" />

</RelativeLayout>

</LinearLayout>


注:以上代码仅供参考
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: