1.依赖

annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'compile 'com.jakewharton:butterknife:8.8.1'compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'compile 'com.squareup.retrofit2:retrofit:2.3.0'compile 'com.squareup.retrofit2:converter-gson:2.3.0'compile 'com.facebook.fresco:fresco:0.12.0'compile 'com.facebook.fresco:animated-base-support:0.12.0'compile 'com.facebook.fresco:animated-webp:0.12.0'compile 'com.facebook.fresco:webpsupport:0.12.0'compile 'io.reactivex.rxjava2:rxjava:2.1.7'compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'compile 'io.reactivex.rxjava2:rxandroid:2.0.1'compile 'com.squareup.okhttp3:okhttp:3.9.0'compile 'com.google.code.gson:gson:2.8.1'

2.布局

1.加减器布局   layout_add_delete

<?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:orientation="horizontal"android:weightSum="1"><TextViewandroid:id="@+id/txt_delete"android:layout_width="30dp"android:layout_height="30dp"android:text="减"android:gravity="center"android:background="#8b948b"/><EditTextandroid:id="@+id/et_number"android:layout_marginTop="2dp"android:layout_width="50dp"android:layout_height="30dp"android:background="@drawable/edit"android:layout_weight="0.00"android:gravity="center"android:text="1"/><TextViewandroid:id="@+id/txt_add"android:layout_width="30dp"android:layout_height="30dp"android:text="加"android:gravity="center"android:background="#8b948b"/></LinearLayout>

2. 商品详情布局   activity_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:fresco="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><com.facebook.drawee.view.SimpleDraweeViewandroid:id="@+id/my_image_view"android:layout_width="match_parent"android:layout_height="450dp"fresco:placeholderImage="@mipmap/ic_launcher" /><TextViewandroid:id="@+id/goods_title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="10dp"android:text="a啊啊是你的"android:textSize="20dp" /><TextViewandroid:id="@+id/goods_price"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="10dp"android:text="¥ 18132"android:textColor="#dc5f2e"android:textSize="18dp" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="10dp"android:text="我是商家19"android:textSize="16dp" /></LinearLayout><LinearLayoutandroid:layout_alignParentBottom="true"android:layout_width="match_parent"android:layout_height="50dp"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_addcart"android:layout_weight="1"android:layout_width="0dp"android:layout_height="match_parent"android:background="#ffc207"android:text="加入购物车"/><Buttonandroid:id="@+id/btn_shopping"android:layout_weight="1"android:layout_width="0dp"android:layout_height="match_parent"android:background="#ff6b06"android:text="立即购买"/></LinearLayout></RelativeLayout>

3.购物车布局 activity_main2

<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><!--头布局--><LinearLayoutandroid:id="@+id/top_bar"android:layout_width="match_parent"android:layout_height="48dp"android:background="#f7f7f7"android:orientation="vertical" ><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="48dp"android:background="@android:color/transparent"android:orientation="vertical" ><ImageViewandroid:id="@+id/back"android:layout_width="48dp"android:layout_height="48dp"android:layout_alignParentLeft="true"android:layout_gravity="center_vertical"android:padding="12dp"android:src="@drawable/back" /><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center"android:minHeight="48dp"android:text="购物车"android:textColor="#1a1a1a"android:textSize="16sp" /><TextViewandroid:id="@+id/edit"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_marginRight="40dp"android:gravity="center"android:minHeight="48dp"android:text="编辑"android:textColor="#1a1a1a"android:textSize="14sp"android:visibility="visible" /></RelativeLayout></LinearLayout><ExpandableListViewandroid:id="@+id/exListView"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"android:childIndicator="@null"android:groupIndicator="@null" ></ExpandableListView><LinearLayoutandroid:layout_width="match_parent"android:layout_height="50dp"android:gravity="center_vertical"android:orientation="horizontal" ><CheckBoxandroid:id="@+id/all_chekbox"android:layout_marginLeft="20dp"android:layout_width="wrap_content"android:layout_height="wrap_content" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="全选"/><LinearLayoutandroid:id="@+id/ll_info"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="4"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"android:layout_marginRight="20dp"android:layout_weight="1"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:gravity="right"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="5dp"android:text="合计:"android:textSize="18sp"android:textStyle="bold" /><TextViewandroid:id="@+id/total_price"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="¥0.00"android:textColor="#f23232"android:textSize="16sp"android:textStyle="bold" /></LinearLayout><TextViewandroid:id="@+id/total_number"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="共有商品:0件"android:gravity="right"android:textSize="16sp"android:textStyle="bold" /></LinearLayout><TextViewandroid:id="@+id/tv_go_to_pay"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="3"android:background="#fd7a05"android:clickable="true"android:gravity="center"android:text="结算"android:textColor="#FAFAFA"/><TextViewandroid:id="@+id/tv_go_to_del"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="3"android:background="#e2231c"android:clickable="true"android:gravity="center"android:text="删除"android:textColor="#FAFAFA"android:visibility="gone"/></LinearLayout></LinearLayout>
</LinearLayout>

4.二级列表组级布局 ex_group_item

<?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="#cfc3c3"android:orientation="horizontal"><CheckBoxandroid:id="@+id/group_checkbox"android:layout_marginLeft="20dp"android:layout_width="wrap_content"android:layout_height="wrap_content"android:focusable="false"/><TextViewandroid:id="@+id/shop_name"android:layout_marginLeft="20dp"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="16dp" /></LinearLayout>

5.二级列表子布局  ex_child_item

<?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:fresco="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="230dp"android:orientation="horizontal"><CheckBoxandroid:id="@+id/child_checkbox"android:layout_marginTop="50dp"android:layout_marginLeft="20dp"android:layout_marginBottom="50dp"android:layout_width="wrap_content"android:layout_height="wrap_content"/><RelativeLayoutandroid:layout_marginLeft="20dp"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:id="@+id/shop_title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:layout_marginLeft="17dp"android:layout_marginStart="17dp"android:text="TextView"android:layout_alignParentTop="true" /><!--<ImageViewandroid:id="@+id/shop_img"android:layout_width="90dp"android:layout_height="90dp"android:layout_marginTop="30dp"app:srcCompat="@mipmap/ic_launcher"android:layout_below="@+id/shop_name"android:layout_alignParentLeft="true"android:layout_alignParentStart="true" />--><com.facebook.drawee.view.SimpleDraweeViewandroid:id="@+id/shop_img"android:layout_width="90dp"android:layout_height="90dp"android:layout_marginTop="30dp"fresco:placeholderImage="@mipmap/ic_launcher"android:layout_below="@+id/shop_name"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"/><TextViewandroid:id="@+id/shop_price"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignTop="@+id/shop_img"android:layout_centerHorizontal="true"android:layout_marginTop="10dp"android:text="¥20"android:textColor="#f23232"/><com.bwei.gepeng.myview.AddDeleteViewandroid:id="@+id/adv"android:layout_width="160dp"android:layout_height="30dp"android:layout_below="@+id/shop_price"android:layout_marginTop="30dp"android:layout_marginLeft="140dp"app:left_text="-"app:right_text="+"app:middle_text="1"android:focusable="false"></com.bwei.gepeng.myview.AddDeleteView><Buttonandroid:id="@+id/shop_delete"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentEnd="true"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:visibility="invisible"android:text="删除" /></RelativeLayout></LinearLayout>

3.实体类

1. MessageBean

package com.bwei.gepeng.entity;public class MessageBean <T>{private String code;private T data;private String msg;private SellerBean seller;public String getCode() {return code;}public void setCode(String code) {this.code = code;}public T getData() {return data;}public void setData(T data) {this.data = data;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public SellerBean getSeller() {return seller;}public void setSeller(SellerBean seller) {this.seller = seller;}public static class SellerBean {/*** description : 我是商家19* icon : http://120.27.23.105/images/icon.png* name : 商家19* productNums : 999* score : 5.0* sellerid : 19*/private String description;private String icon;private String name;private int productNums;private double score;private int sellerid;public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getIcon() {return icon;}public void setIcon(String icon) {this.icon = icon;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getProductNums() {return productNums;}public void setProductNums(int productNums) {this.productNums = productNums;}public double getScore() {return score;}public void setScore(double score) {this.score = score;}public int getSellerid() {return sellerid;}public void setSellerid(int sellerid) {this.sellerid = sellerid;}}
}

2.GoodsShowBean

package com.bwei.gepeng.entity;public class GoodsShowBean {private double bargainPrice;private String createtime;private String detailUrl;private String images;private int itemtype;private int pid;private double price;private int pscid;private int salenum;private int sellerid;private String subhead;private String title;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 getItemtype() {return itemtype;}public void setItemtype(int itemtype) {this.itemtype = itemtype;}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 getSalenum() {return salenum;}public void setSalenum(int salenum) {this.salenum = salenum;}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;}@Overridepublic String toString() {return "GoodsShowBean{" +"bargainPrice=" + bargainPrice +", createtime='" + createtime + '\'' +", detailUrl='" + detailUrl + '\'' +", images='" + images + '\'' +", itemtype=" + itemtype +", pid=" + pid +", price=" + price +", pscid=" + pscid +", salenum=" + salenum +", sellerid=" + sellerid +", subhead='" + subhead + '\'' +", title='" + title + '\'' +'}';}
}

3. CartBean

package com.bwei.gepeng.entity;import java.util.List;public class CartBean {private String sellerName;private String sellerid;private List<ListBean> list;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 {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;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;}}@Overridepublic String toString() {return "CartBean{" +"sellerName='" + sellerName + '\'' +", sellerid='" + sellerid + '\'' +", list=" + list +'}';}
}

4. GroupBean

package com.bwei.gepeng.entity;public class GroupBean {private String sellerName;private boolean gropuCb;public GroupBean(String sellerName, boolean gropuCb) {this.sellerName = sellerName;this.gropuCb = gropuCb;}public String getSellerName() {return sellerName;}public void setSellerName(String sellerName) {this.sellerName = sellerName;}public boolean isGropuCb() {return gropuCb;}public void setGropuCb(boolean gropuCb) {this.gropuCb = gropuCb;}@Overridepublic String toString() {return "GroupBean{" +"sellerName='" + sellerName + '\'' +", gropuCb=" + gropuCb +'}';}
}

5.ChildBean

package com.bwei.gepeng.entity;public class ChildBean {private String title;private String images;private double price;private int num;private boolean childCb;private boolean btn;private int pid;public ChildBean(String title, String images, double price, int num, boolean childCb, boolean btn, int pid) {this.title = title;this.images = images;this.price = price;this.num = num;this.childCb = childCb;this.btn = btn;this.pid = pid;}public int getPid() {return pid;}public void setPid(int pid) {this.pid = pid;}public boolean isBtn() {return btn;}public void setBtn(boolean btn) {this.btn = btn;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getImages() {return images;}public void setImages(String images) {this.images = images;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public boolean isChildCb() {return childCb;}public void setChildCb(boolean childCb) {this.childCb = childCb;}@Overridepublic String toString() {return "ChildBean{" +"title='" + title + '\'' +", images='" + images + '\'' +", price=" + price +", num=" + num +", childCb=" + childCb +", btn=" + btn +", pid=" + pid +'}';}
}

4.接口

1.ApiService
package com.bwei.gepeng.http;import com.bwei.gepeng.entity.CartBean;
import com.bwei.gepeng.entity.GoodsShowBean;
import com.bwei.gepeng.entity.MessageBean;import java.util.List;
import java.util.Map;import io.reactivex.Flowable;
import retrofit2.http.GET;
import retrofit2.http.QueryMap;public interface ApiService {//查询商品详情75//http://120.27.23.105/product/getProductDetail?pid=75&source=android@GET("product/getProductDetail")Flowable<MessageBean<GoodsShowBean>> getNews(@QueryMap Map<String,String> map);//查询购物车//http://120.27.23.105/product/getCarts?uid=3802&source=android@GET("product/getCarts")Flowable<MessageBean<List<CartBean>>> getCart(@QueryMap Map<String,String> map);//删除购物车//http://120.27.23.105/product/getCarts?uid=3802&source=android@GET("product/deleteCart")Flowable<MessageBean<List<CartBean>>> getDel(@QueryMap Map<String,String> map);//添加购物车//http://120.27.23.105/product/addCart?uid=3802&pid=75&source=android@GET("product/addCart")Flowable<MessageBean<List<CartBean>>> getAdd(@QueryMap Map<String,String> map);
}

2.IView

public interface IView {void OnSuccess(Object o,String tag);void OnFailed(Exception e,String tag);
}

3.IPresenter

import java.util.Map;public interface IPresenter {void getData(Map<String,String> map, String tag);
}

4.IModel

import java.util.Map;public interface IModel {void getData(Map<String,String> map,String tag);
}

5.代码

1.自定义View 加减器 AddDeleteView
package com.bwei.gepeng.myview;import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;import com.bwei.gepeng.R;public class AddDeleteView extends LinearLayout {private OnAddDelClickListener listener;private EditText etNumber;//对外提供一个点击的回调接口public interface OnAddDelClickListener{void onAddClick(View v);void onDelClick(View v);}public void setOnAddDelClickListener(OnAddDelClickListener listener){if(listener!=null){this.listener=listener;}}public AddDeleteView(Context context) {this(context,null);}public AddDeleteView(Context context, AttributeSet attrs) {this(context, attrs,0);}public AddDeleteView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);initView(context, attrs, defStyleAttr);}private void initView(Context context, AttributeSet attrs, int defStyleAttr) {View.inflate(context, R.layout.layout_add_delete,this);//获取控件TextView txtDelete=findViewById(R.id.txt_delete);TextView txtAdd=findViewById(R.id.txt_add);etNumber = findViewById(R.id.et_number);TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AddDeleteViewStyle);String leftText = typedArray.getString(R.styleable.AddDeleteViewStyle_left_text);String rightText = typedArray.getString(R.styleable.AddDeleteViewStyle_right_text);String middleText = typedArray.getString(R.styleable.AddDeleteViewStyle_middle_text);int color = typedArray.getColor(R.styleable.AddDeleteViewStyle_left_text_color, Color.RED);txtDelete.setText(leftText);txtAdd.setText(rightText);etNumber.setText(middleText);txtDelete.setTextColor(color);//回收typedArray.recycle();txtDelete.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View view) {listener.onDelClick(view);}});txtAdd.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View view) {listener.onAddClick(view);}});}//对外提供一个修改数字的方法public void setNumber(int number){if(number>0){etNumber.setText(number+"");}}//对外提供一个获取当前数字的方法public int getNumber(){String string = etNumber.getText().toString();int i = Integer.parseInt(string);return i;}}

2.Retrofit工具类 RetrofitUtils

package com.bwei.gepeng.http;import java.io.IOException;import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;public class RetrofitUtils {private static volatile RetrofitUtils instance;private final Retrofit retrofit;private RetrofitUtils(){OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Logger()).build();retrofit = new Retrofit.Builder().client(client).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create()).baseUrl("http://120.27.23.105/").build();}public static RetrofitUtils getInstance(){if(instance==null){synchronized (RetrofitUtils.class){if(instance==null){instance=new RetrofitUtils();}}}return instance;}public ApiService getApiService(){ApiService apiService = retrofit.create(ApiService.class);return apiService;}class Logger implements Interceptor {@Overridepublic 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);}}
}

3.M层

package com.bwei.gepeng.model;import com.bwei.gepeng.entity.CartBean;
import com.bwei.gepeng.entity.GoodsShowBean;
import com.bwei.gepeng.entity.MessageBean;
import com.bwei.gepeng.http.RetrofitUtils;
import com.bwei.gepeng.presenter.NewsPresenter;import java.util.List;
import java.util.Map;import io.reactivex.Flowable;public class Model implements IModel{private NewsPresenter presenter;public Model(NewsPresenter presenter) {this.presenter = presenter;}@Overridepublic void getData(Map<String, String> map, String tag) {if(tag.equals("cart")){Flowable<MessageBean<List<CartBean>>> flowable = RetrofitUtils.getInstance().getApiService().getCart(map);presenter.get2(flowable,tag);}else if(tag.equals("goods")){Flowable<MessageBean<GoodsShowBean>> flowable = RetrofitUtils.getInstance().getApiService().getNews(map);presenter.get(flowable,tag);}else if(tag.equals("del")){Flowable<MessageBean<List<CartBean>>> flowable = RetrofitUtils.getInstance().getApiService().getDel(map);presenter.get3(flowable,tag);}else if(tag.equals("add")){Flowable<MessageBean<List<CartBean>>> flowable = RetrofitUtils.getInstance().getApiService().getAdd(map);presenter.get4(flowable,tag);}}
}

4.P层

package com.bwei.gepeng.presenter;import com.bwei.gepeng.entity.CartBean;
import com.bwei.gepeng.entity.GoodsShowBean;
import com.bwei.gepeng.entity.MessageBean;
import com.bwei.gepeng.model.Model;
import com.bwei.gepeng.view.IView;import java.util.List;
import java.util.Map;import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;public class NewsPresenter implements IPresenter{private IView iView;private DisposableSubscriber<MessageBean<GoodsShowBean>> subscriber;private DisposableSubscriber<MessageBean<List<CartBean>>> subscriber2;private DisposableSubscriber<MessageBean<List<CartBean>>> subscriber3;private DisposableSubscriber<MessageBean<List<CartBean>>> subscriber4;public void attachView(IView iView){this.iView=iView;}@Overridepublic void getData(Map<String, String> map, String tag) {Model model = new Model(this);model.getData(map,tag);}public void detachView(){if(iView!=null){iView=null;}if(subscriber!=null){if(!subscriber.isDisposed()){subscriber.dispose();}}if(subscriber2!=null){if(!subscriber2.isDisposed()){subscriber2.dispose();}}if(subscriber3!=null){if(!subscriber3.isDisposed()){subscriber3.dispose();}}if(subscriber4!=null){if(!subscriber4.isDisposed()){subscriber4.dispose();}}}//查询购物车public void get(Flowable<MessageBean<GoodsShowBean>> flowable , final String tag) {subscriber = flowable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new DisposableSubscriber<MessageBean<GoodsShowBean>>() {@Overridepublic void onNext(MessageBean<GoodsShowBean> listMessageBean) {if (listMessageBean != null) {GoodsShowBean data = listMessageBean.getData();iView.OnSuccess(data,tag);}}@Overridepublic void onError(Throwable t) {iView.OnFailed(new Exception(t),tag);}@Overridepublic void onComplete() {}});}//查询商品详情75public void get2(Flowable<MessageBean<List<CartBean>>> flowable, final String tag) {subscriber2 = flowable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new DisposableSubscriber<MessageBean<List<CartBean>>>() {@Overridepublic void onNext(MessageBean<List<CartBean>> list) {if (list != null) {List<CartBean> data = list.getData();if(data!=null){iView.OnSuccess(data,tag);}}}@Overridepublic void onError(Throwable t) {iView.OnFailed(new Exception(t),tag);}@Overridepublic void onComplete() {}});}//删除购物车public void get3(Flowable<MessageBean<List<CartBean>>> flowable, final String tag) {subscriber3 = flowable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new DisposableSubscriber<MessageBean<List<CartBean>>>() {@Overridepublic void onNext(MessageBean<List<CartBean>> list) {if (list != null) {String code = list.getMsg();iView.OnSuccess(code,tag);}}@Overridepublic void onError(Throwable t) {iView.OnFailed(new Exception(t),tag);}@Overridepublic void onComplete() {}});}//添加购物车public void get4(Flowable<MessageBean<List<CartBean>>> flowable, final String tag) {subscriber4 = flowable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new DisposableSubscriber<MessageBean<List<CartBean>>>() {@Overridepublic void onNext(MessageBean<List<CartBean>> list) {if (list != null) {String code = list.getMsg();iView.OnSuccess(code,tag);}}@Overridepublic void onError(Throwable t) {iView.OnFailed(new Exception(t),tag);}@Overridepublic void onComplete() {}});}
}

5.MainActivity 商品详情页面

package com.bwei.gepeng.view;import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;import com.bwei.gepeng.R;
import com.bwei.gepeng.entity.GoodsShowBean;
import com.bwei.gepeng.presenter.NewsPresenter;
import com.facebook.drawee.view.SimpleDraweeView;import java.util.HashMap;
import java.util.Map;import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;public class MainActivity extends AppCompatActivity implements IView {@BindView(R.id.my_image_view)SimpleDraweeView myImageView;@BindView(R.id.goods_title)TextView goodsTitle;@BindView(R.id.goods_price)TextView goodsPrice;private NewsPresenter presenter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ButterKnife.bind(this);presenter = new NewsPresenter();presenter.attachView(this);//http://120.27.23.105/product/getProductDetail?pid=75&source=androidMap<String, String> map = new HashMap<>();map.put("pid", "75");presenter.getData(map, "goods");}@Overridepublic void OnSuccess(Object o, String tag) {if (tag.equals("goods")) {if (o != null) {GoodsShowBean data = (GoodsShowBean) o;//Log.e("Gp", "OnSuccess: " + data.toString());myImageView.setImageURI(data.getImages().split("\\|")[0]);goodsTitle.setText(data.getTitle());goodsPrice.setText("¥ "+data.getPrice());}}else if(tag.equals("add")){if (o != null) {String msg = (String) o;Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();}}}@Overridepublic void OnFailed(Exception e, String tag) {}@OnClick({R.id.btn_addcart, R.id.btn_shopping})public void onViewClicked(View view) {switch (view.getId()) {case R.id.btn_addcart:Map<String, String> map = new HashMap<>();map.put("uid", "3802");map.put("pid", "75");presenter.getData(map, "add");//Toast.makeText(MainActivity.this,"添加成功",Toast.LENGTH_SHORT).show();break;case R.id.btn_shopping:Intent intent=new Intent(MainActivity.this,Main2Activity.class);startActivity(intent);break;}}
}

6.二级列表适配器 ExpandableAdapter

package com.bwei.gepeng.adapter;import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;import com.bwei.gepeng.R;
import com.bwei.gepeng.entity.ChildBean;
import com.bwei.gepeng.entity.GroupBean;
import com.bwei.gepeng.myview.AddDeleteView;
import com.bwei.gepeng.view.Main2Activity;
import com.facebook.drawee.view.SimpleDraweeView;import java.util.ArrayList;
import java.util.List;public class ExpandableAdapter extends BaseExpandableListAdapter {private Context context;private List<GroupBean> groupBeen=new ArrayList<>();private List<List<ChildBean>> childBeen=new ArrayList<>();private Main2Activity main;public ExpandableAdapter(Context context, List<GroupBean> groupBeen, List<List<ChildBean>> childBeen) {this.context = context;this.groupBeen = groupBeen;this.childBeen = childBeen;this.main = (Main2Activity) context;}//接口回调private onDeleteGoods onDleGoods;public interface onDeleteGoods{void onDelGoods(int i,int i1,String pid);}public void setOnDeleteGoods(onDeleteGoods onDleGoods){this.onDleGoods=onDleGoods;}@Overridepublic int getGroupCount() {return groupBeen.size();}@Overridepublic int getChildrenCount(int i) {return childBeen.get(i).size();}@Overridepublic Object getGroup(int i) {return groupBeen.get(i).getSellerName();}@Overridepublic Object getChild(int i, int i1) {return childBeen.get(i).get(i1).getTitle();}@Overridepublic long getGroupId(int i) {return i;}@Overridepublic long getChildId(int i, int i1) {return i1;}@Overridepublic boolean hasStableIds() {return false;}//一级组@Overridepublic View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {//加载视图view=View.inflate(context, R.layout.ex_group_item ,null);final CheckBox groupCb= view.findViewById(R.id.group_checkbox);TextView shopName= view.findViewById(R.id.shop_name);shopName.setText(groupBeen.get(i).getSellerName());groupCb.setChecked(groupBeen.get(i).isGropuCb());//组复选按钮groupCb.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {boolean gchecked = groupCb.isChecked();groupBeen.get(i).setGropuCb(gchecked);//Main2Activity main= (Main2Activity) context;for(GroupBean i: groupBeen){boolean gropuCb = i.isGropuCb();if(!gropuCb){main.allCheckbox.setChecked(false);break;}else{main.allCheckbox.setChecked(true);}}int size = childBeen.get(i).size();if(gchecked){for(int r=0;r<size;r++){//Toast.makeText(context,"group按钮"+ gchecked+""+size, Toast.LENGTH_SHORT).show();childBeen.get(i).get(r).setChildCb(true);}}else{for(int r=0;r<size;r++){//Toast.makeText(context,"group按钮"+ gchecked+""+size, Toast.LENGTH_SHORT).show();childBeen.get(i).get(r).setChildCb(false);}}notifyDataSetChanged();main.changesum(childBeen);}});return view;}//二级组@Overridepublic View getChildView(final int i, final int i1, boolean b, View v, ViewGroup viewGroup) {//加载视图v=View.inflate(context, R.layout.ex_child_item ,null);final CheckBox childCb = v.findViewById(R.id.child_checkbox);TextView shopTitle= v.findViewById(R.id.shop_title);TextView shopPrice= v.findViewById(R.id.shop_price);//ImageView shopImg=v.findViewById(R.id.shop_img);//draweeView.setImageURI(uri);SimpleDraweeView shopImg = v.findViewById(R.id.shop_img);final AddDeleteView adv = v.findViewById(R.id.adv);Button shop_delete=v.findViewById(R.id.shop_delete);childCb.setChecked(childBeen.get(i).get(i1).isChildCb());String images = childBeen.get(i).get(i1).getImages();//Glide.with(context).load(images).into(shopImg);shopImg.setImageURI(images);shopTitle.setText(childBeen.get(i).get(i1).getTitle());shopPrice.setText(childBeen.get(i).get(i1).getPrice()+"");adv.setNumber(childBeen.get(i).get(i1).getNum());//final Main2Activity main= (Main2Activity) context;//控制删除按钮的显隐if(childBeen.get(i).get(i1).isBtn()){shop_delete.setVisibility(View.VISIBLE);}else{shop_delete.setVisibility(View.INVISIBLE);}//删除按钮监听shop_delete.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {onDleGoods.onDelGoods(i,i1,childBeen.get(i).get(i1).getPid()+"");}});//加减器逻辑adv.setOnAddDelClickListener(new AddDeleteView.OnAddDelClickListener() {@Overridepublic void onAddClick(View v) {int number = adv.getNumber();number++;adv.setNumber(number);childBeen.get(i).get(i1).setNum(number);main.changesum(childBeen);}@Overridepublic void onDelClick(View v) {int number = adv.getNumber();if(number==1){Toast.makeText(context,"用户最小数量为1",Toast.LENGTH_SHORT).show();}number--;adv.setNumber(number);childBeen.get(i).get(i1).setNum(number);main.changesum(childBeen);}});//二级组的复选框监听childCb.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {boolean flag=false;boolean cchecked = childCb.isChecked();childBeen.get(i).get(i1).setChildCb(cchecked);//Toast.makeText(context,"child按钮"+ cchecked+""+i1, Toast.LENGTH_SHORT).show();// Main2Activity main= (Main2Activity) context;for (List<ChildBean> i1:childBeen){for(int r=0;r<i1.size();r++) {boolean childCb1 = i1.get(r).isChildCb();if(!childCb1){main.allCheckbox.setChecked(false);groupBeen.get(i).setGropuCb(false);flag=true;break;}else{main.allCheckbox.setChecked(true);groupBeen.get(i).setGropuCb(true);}}if(flag){break;}}int size = childBeen.get(i).size();for(int x=0;x<size;x++) {boolean childCb1 = childBeen.get(i).get(x).isChildCb();if(!childCb1){groupBeen.get(i).setGropuCb(false);break;}else{groupBeen.get(i).setGropuCb(true);}}notifyDataSetChanged();main.changesum(childBeen);}});return v;}@Overridepublic boolean isChildSelectable(int i, int i1) {return false;}
}

7.购物车页面逻辑 Main2Activity

package com.bwei.gepeng.view;import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;import com.bwei.gepeng.R;
import com.bwei.gepeng.adapter.ExpandableAdapter;
import com.bwei.gepeng.entity.CartBean;
import com.bwei.gepeng.entity.ChildBean;
import com.bwei.gepeng.entity.GroupBean;
import com.bwei.gepeng.presenter.NewsPresenter;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;public class Main2Activity extends AppCompatActivity implements IView {@BindView(R.id.exListView)ExpandableListView exListView;@BindView(R.id.all_chekbox)public CheckBox allCheckbox;@BindView(R.id.total_price)TextView totalPrice;@BindView(R.id.total_number)TextView totalnumber;@BindView(R.id.tv_go_to_pay)TextView tvGoToPay;@BindView(R.id.tv_go_to_del)TextView tvGoToDel;private ExpandableAdapter expandableAdapter;private boolean flagedit = true;private boolean flagdel = false;private NewsPresenter presenter;List<GroupBean> groupBeen = new ArrayList<>();List<List<ChildBean>> childBeen = new ArrayList<>();int i;int i1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main2);ButterKnife.bind(this);//获取二级列表适配器expandableAdapter = new ExpandableAdapter(Main2Activity.this, groupBeen, childBeen);exListView.setAdapter(expandableAdapter);exListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {@Overridepublic boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {return true;}});presenter = new NewsPresenter();presenter.attachView(this);//http://120.27.23.105/product/getCarts?uid=3802&source=androidMap<String, String> map = new HashMap<>();map.put("uid", "3802");presenter.getData(map, "cart");expandableAdapter.setOnDeleteGoods(new ExpandableAdapter.onDeleteGoods() {@Overridepublic void onDelGoods(int i, int i1, String pid) {Main2Activity.this.i = i;Main2Activity.this.i1 = i1;Map<String, String> map = new HashMap<>();map.put("uid", "3802");map.put("pid", pid);presenter.getData(map, "del");}});}@Overridepublic void OnSuccess(Object o, String tag) {if (tag.equals("cart")) {if (o != null) {List<CartBean> data = (List<CartBean>) o;for (CartBean i : data) {GroupBean groupBean = new GroupBean(i.getSellerName(), false);this.groupBeen.add(groupBean);List<CartBean.ListBean> list = i.getList();List<ChildBean> ls = new ArrayList<>();for (CartBean.ListBean w : list) {String[] split = w.getImages().split("\\|");ChildBean childBean = new ChildBean(w.getTitle(), split[0], w.getPrice(), 1, false, false, w.getPid());ls.add(childBean);}this.childBeen.add(ls);}for (int i = 0; i < expandableAdapter.getGroupCount(); i++) {exListView.expandGroup(i);}}} else if (tag.equals("del")) {if (o != null) {String msg = (String) o;if (this.i != -1 && this.i1 != -1) {int size = childBeen.get(i).size();if (size == 1) {childBeen.remove(i);groupBeen.remove(i);} else {childBeen.get(i).remove(i1);}changesum(childBeen);this.i = -1;this.i1 = -1;if(flagdel){delGoods();}}}}expandableAdapter.notifyDataSetChanged();}@Overridepublic void OnFailed(Exception e, String tag) {}@OnClick({R.id.back, R.id.edit, R.id.all_chekbox,R.id.tv_go_to_del})public void onViewClicked(View view) {switch (view.getId()) {case R.id.back:finish();break;case R.id.edit:if(flagedit){tvGoToPay.setVisibility(View.GONE);tvGoToDel.setVisibility(View.VISIBLE);}else{tvGoToPay.setVisibility(View.VISIBLE);tvGoToDel.setVisibility(View.GONE);}for (List<ChildBean> i1 : childBeen) {for (int r = 0; r < i1.size(); r++) {i1.get(r).setBtn(flagedit);}}flagedit = !flagedit;expandableAdapter.notifyDataSetChanged();break;case R.id.all_chekbox:boolean checked = allCheckbox.isChecked();//改变一级item复选框for (GroupBean i : groupBeen) {i.setGropuCb(checked);}//改变二级item复选框for (List<ChildBean> i1 : childBeen) {for (int r = 0; r < i1.size(); r++) {i1.get(r).setChildCb(checked);}}expandableAdapter.notifyDataSetChanged();changesum(childBeen);break;case R.id.tv_go_to_del:if(childBeen.size()!=0){for (List<ChildBean> i1 : childBeen) {for (int r = 0; r < i1.size(); r++) {boolean childCb1 = i1.get(r).isChildCb();if (childCb1) {flagdel=true;delGoods();if(allCheckbox.isChecked()){allCheckbox.setChecked(false);}break;}}if(flagdel){break;}}}//Toast.makeText(Main2Activity.this,flagdel+"",Toast.LENGTH_SHORT).show();break;}}//递归删除private void delGoods(){Boolean flag=false;for(int p=0;p<childBeen.size();p++) {for (int r = 0; r < childBeen.get(p).size(); r++) {boolean childCb1 = childBeen.get(p).get(r).isChildCb();if(p==childBeen.size()-1&&r==childBeen.get(p).size()-1){flagdel=false;}if (childCb1) {int pid = childBeen.get(p).get(r).getPid();this.i = p;this.i1 = r;Map<String, String> map = new HashMap<>();map.put("uid", "3802");map.put("pid", pid+"");presenter.getData(map, "del");flag=!flag;break;}}if(flag){break;}}}//计算和数量总价public void changesum(List<List<ChildBean>> childBeen) {int count = 0;double sum = 0;for (List<ChildBean> i1 : childBeen) {for (int r = 0; r < i1.size(); r++) {boolean childCb1 = i1.get(r).isChildCb();if (childCb1) {double price = i1.get(r).getPrice();int num = i1.get(r).getNum();sum += price * num;count++;}}}totalPrice.setText("¥" + sum);totalnumber.setText("共有商品:" + count + "件");}
}

6.附

shape图 edit
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#FFFFFF" /><!--<corners android:radius="3dip"/>--><strokeandroid:width="1dip"android:color="#BDC7D8" />
</shape>
Application 初始化Fresco
import android.app.Application;
import com.facebook.drawee.backends.pipeline.Fresco;public class App extends Application{@Overridepublic void onCreate() {super.onCreate();Fresco.initialize(this);}
}

												

Rxjava+Retrofit+MVP实现购物车Mode相关推荐

  1. RxJava+Retrofit+Mvp实现购物车(没有结算页面)

    先给大家展示一下效果图 框架结构: 1.项目框架:MVP,图片加载用Fresco,网络请求用OKhttp+Retrofit实现(自己封装,加单例模式), 2.完成购物车数据添加(如果接口无数据,可用接 ...

  2. Rxjava+Retrofit+Mvp的使用实例(基于retrofit2.1.0)

    1.MVP介绍 在Android项目中,Activity和Fragment占据了大部分的开发工作.如果有一种设计模式(或者说代码结构)专门是为优化Activity和Fragment的代码而产生的,你说 ...

  3. Android RxJava+Retrofit+MVP 入门总结

    前言 RxJava+Retrofit+MVP的使用已经推出一段时间了,也一直想找个时间学习一下并且应用到接下来的项目中.趁放假这段时间仔细研究了一下,确实相比于其他框架的学习成本要高一些,不过功能实现 ...

  4. RxJava+Retrofit+MVP+Dagger2

    传说中的谷歌四件套,按顺序来哈~ 2017.2.20更新:对于用了一段时间的谷歌四件套的开发者们来说,基础应该都已经掌握的差不多了,但是四件套确实很博大精深,要想完全掌握,一是要学习使用技巧,二是要在 ...

  5. Android开发模式之RxJava+Retrofit+MVP(kotlin)

    一共分为两部分,第一部分是RxJava+Retrofit网络请求的使用,一部分是MVP模式结合网络请求 一,RxJava+Retrofit的使用 ①module引入 里面已经封装了OkHttp和Gso ...

  6. android小说阅读、MVP + RxJava + Retrofit项目、证件拍照裁剪、蓝牙锁等源码

    Android精选源码 完全防美团设置支付密码,页面与细节完全一致,如不能... android智能选股应用源码 android开源小说阅读app源码(Kotlin) Android模仿Duoling ...

  7. android小说阅读、MVP + RxJava + Retrofit项目、证件拍照裁剪、蓝牙锁等源码器

    Android精选源码 完全防美团设置支付密码,页面与细节完全一致,如不能- android智能选股应用源码 android开源小说阅读app源码(Kotlin) Android模仿Duolingo的 ...

  8. 一款在线视频 App,基于 Material Design + MVP + RxJava + Retrofit + Realm + Glide

    Ghost 项目地址:GeekGhost/Ghost 简介:一款在线视频 App,基于 Material Design + MVP + RxJava + Retrofit + Realm + Glid ...

  9. TLint for 虎扑体育 基于Dagger2+RxJava+Retrofit开发,采用MVP模式

    TLint 类别: 完整源码 打分: ★★★★★ 更新: 2016-05-12 09:54 大小: 6976 kb 开发环境: Android Studio 浏览: 484 次 下载: 83 次 项目 ...

最新文章

  1. 函数 php_PHP函数缺陷详解
  2. Github 工作流程
  3. python编译exe文件太大了_python编译windows下可执行的exe文件
  4. 11月17日学习内容整理:jquery文档处理,事件细讲,动画
  5. WPF获取鼠标相对于屏幕的绝对位置
  6. centos6 mysql密码_CentOS6.5下修改MySQL密码
  7. 使用 typescript ,提升 vue 项目的开发体验(1)
  8. 前端学习(3105):react-hello-jsx语法规则
  9. python爬虫框架scrapy操作步骤
  10. HTML简介与历史版本
  11. JAVA学习经验--总结JAVA抽象类和接口
  12. 双显卡单独分辨率_甜点光追显卡—带你实现GAMING梦!!!
  13. 一个简单的基于 DirectShow 的播放器 2(对话框类)
  14. 【转】TreeList 选中节点时图标状态和背景色
  15. flask如何查询mysql_如何从Flask应用中的MySQL查询返回数据?
  16. 凯斯西储大学计算机科学硕士,凯斯西储大学电气工程与计算机科学系
  17. CCSK云安全认证-M2-云基础设施安全
  18. seo关键词优化的技巧
  19. python子图加标题_python – matplotlib的子图中的行和列标题
  20. 射极跟随器的负载加重情况

热门文章

  1. Flink CDC 系列(3)—— Flink CDC MySQL Connector 与 Flink SQL 的结合使用案例Demo
  2. 为何物流对供应链如此重要?
  3. Golang基本数据结构
  4. 服务器跨站脚本漏洞修复,如何修复XSS跨站脚本漏洞?
  5. Photoshop CC油画滤镜实例教程讲解
  6. 史蒂夫·鲍尔默也用Firefox和Google
  7. interFoam进行两相流模拟的一些典型参数设置对比paraview绘制相界面的方法
  8. 《环境科学与管理》期刊简介
  9. skype默认占用80和443port
  10. 幕墙:观察样板制作标准化指引