您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在RxJava中使用Retrofit和Mvp實現購物車,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
框架結構:
1.項目框架:MVP,圖片加載用Fresco,網絡請求用OKhttp+Retrofit實現(自己封裝,加單例模式),
2.完成購物車數據添加(如果接口無數據,可用接口工具添加數據),
3.自定義view實現加減按鈕,每次點擊加減,item中的總數及總價要做出相應的改變。
4.當數量為1時,點擊減號,數量不變,吐司提示用戶最小數量為1。
5.底部總數及總價為所有item項中的總價及總數,每個item中數量價格的更改,底部總價總數要與之聯動
6.實現單選反選全選功能,首次進入默認全選,item未選中時總數及總價不計入底部數據,改變選中狀態時,底部總數及總價能做出正確修改
7.點擊刪除按鈕,刪除item,底部總數及總價能做出正確修改,接口數據刪除。
添加所需要的依賴和聯網權限
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'//Retrofit2所需要的包 compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'//ConverterFactory的Gson依賴包 compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'//ConverterFactory的String依賴包 compile 'io.reactivex.rxjava2:rxjava:2.1.3' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' compile 'de.greenrobot:eventbus:3.0.0-beta1' compile 'com.facebook.fresco:fresco:0.11.0'
<uses-permission android:name="android.permission.INTERNET" />
在使用MVP模式前先分包
net包
API
public class API { public static String HOST="http://120.27.23.105/product/"; }
ServiceAPI
public interface ServiceAPI { @GET("getProductDetail") Flowable<XQBean> getXQ(@Query("pid")int pid, @Query("source")String str); @GET("addCart") Flowable<AddCart> getMsg(@Query("uid")int uid, @Query("pid")int pid, @Query("source")String str); @GET("getCarts") Flowable<CartBean> getCart(@Query("uid")int uid, @Query("source")String str); }
成功的接口
public interface OnNetLisenter<T> { void Success(T t); }
Retrofit的封裝
public class RetrofitHepler { public static OkHttpClient okHttpClient; public static ServiceAPI serViceAPI; /** * 優先執行 */ static { getOkHttpClient(); } public static OkHttpClient getOkHttpClient(){ if(okHttpClient==null){ synchronized (OkHttpClient.class){ if(okHttpClient==null){ okHttpClient=new OkHttpClient(); } } } return okHttpClient; } public static ServiceAPI getSerViceAPI(){ if(serViceAPI==null){ synchronized (OkHttpClient.class){ if(serViceAPI==null){ serViceAPI=onCreate(ServiceAPI.class,API.HOST); } } } return serViceAPI; } public static <T> T onCreate(Class<T>tClass,String url){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); return retrofit.create(tClass); } }
bean包
詳情頁的Bean類
public class XQBean { /** * msg : * seller : {"description":"我是商家2","icon":"http://120.27.23.105/images/icon.png","name":"商家2","productNums":999,"score":5,"sellerid":2} * code : 0 * data : {"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","itemtype":2,"pid":9,"price":78.99,"pscid":1,"salenum":2356,"sellerid":2,"subhead":"每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下","title":"北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g"} */ private String msg; private SellerBean seller; private String code; private DataBean 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 String getCode() { return code; } public void setCode(String code) { this.code = code; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class SellerBean { /** * description : 我是商家2 * icon : http://120.27.23.105/images/icon.png * name : 商家2 * productNums : 999 * score : 5.0 * sellerid : 2 */ 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; } } public static class DataBean { /** * bargainPrice : 111.99 * createtime : 2017-10-14T21:48:08 * detailUrl : https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends * images : https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg * itemtype : 2 * pid : 9 * price : 78.99 * pscid : 1 * salenum : 2356 * sellerid : 2 * subhead : 每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下 * title : 北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g */ 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; } } }
加入購物車的Bean
public class AddCart { 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; } }
商品類
public class CartBean { /** * msg : 請求成功 * code : 0 * data : [{"list":[{"bargainPrice":22.9,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/2542855.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t1930/284/2865629620/390243/e3ade9c4/56f0a08fNbd3a1235.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2137/336/2802996626/155915/e5e90d7a/56f0a09cN33e01bd0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t1882/31/2772215910/389956/c8dbf370/56f0a0a2Na0c86ea6.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2620/166/2703833710/312660/531aa913/57709035N33857877.jpg!q70.jpg","num":1,"pid":24,"price":288,"pscid":2,"selected":0,"sellerid":1,"subhead":"三只松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》","title":"三只松鼠 堅果炒貨 零食奶油味 碧根果225g/袋"},{"bargainPrice":11800,"createtime":"2017-10-10T17:33:37","detailUrl":"https://item.m.jd.com/product/4338107.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6700/155/2098998076/156185/6cf95035/595dd5a5Nc3a7dab5.jpg!q70.jpg","num":2,"pid":57,"price":5199,"pscid":40,"selected":0,"sellerid":1,"subhead":"【i5 MX150 2G顯存】全高清窄邊框 8G內存 256固態硬盤 支持指紋識別 預裝WIN10系統","title":"小米(MI)Air 13.3英寸全金屬輕薄筆記本(i5-7200U 8G 256G PCle SSD MX150 2G獨顯 FHD 指紋識別 Win10)銀\r\n"},{"bargainPrice":99,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/4345173.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6037/35/2944615848/95178/6cd6cff0/594a3a10Na4ec7f39.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6607/258/1025744923/75738/da120a2d/594a3a12Ne3e6bc56.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6370/292/1057025420/64655/f87644e3/594a3a12N5b900606.jpg!q70.jpg","num":1,"pid":45,"price":2999,"pscid":39,"selected":0,"sellerid":1,"subhead":"高清雙攝,就是清晰!2000+1600萬高清攝像頭,6GB大內存+高通驍龍835處理器,性能怪獸!","title":"一加手機5 (A5000) 6GB+64GB 月巖灰 全網通 雙卡雙待 移動聯通電信4G手機"}],"sellerName":"商家1","sellerid":"1"},{"list":[{"bargainPrice":6666,"createtime":"2017-10-10T16:01:31","detailUrl":"https://item.m.jd.com/product/5089273.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t8284/363/1326459580/71585/6d3e8013/59b857f2N6ca75622.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9346/182/1406837243/282106/68af5b54/59b8480aNe8af7f5c.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8434/54/1359766007/56140/579509d9/59b85801Nfea207db.jpg!q70.jpg","num":1,"pid":46,"price":234,"pscid":39,"selected":0,"sellerid":2,"subhead":"【iPhone新品上市】新一代iPhone,讓智能看起來更不一樣","title":"Apple iPhone 8 Plus (A1864) 64GB 金色 移動聯通電信4G手機"}],"sellerName":"商家2","sellerid":"2"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-03T23:43:53","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":5,"pid":12,"price":256,"pscid":1,"selected":0,"sellerid":5,"subhead":"每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下","title":"北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g"}],"sellerName":"商家5","sellerid":"5"},{"list":[{"bargainPrice":11800,"createtime":"2017-10-03T23:53:28","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","num":1,"pid":62,"price":15999,"pscid":40,"selected":0,"sellerid":6,"subhead":"購買電腦辦公部分商品滿1元返火車票5元優惠券(返完即止)","title":"全球購 新款Apple MacBook Pro 蘋果筆記本電腦 銀色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家6","sellerid":"6"},{"list":[{"bargainPrice":399,"createtime":"2017-10-03T23:53:28","detailUrl":"https://item.m.jd.com/product/1439822107.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t5887/201/859509257/69994/6bde9bf6/59224c24Ne854e14c.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5641/233/853609022/57374/5c73d281/59224c24N3324d5f4.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5641/233/853609022/57374/5c73d281/59224c24N3324d5f4.jpg!q70.jpg","num":1,"pid":86,"price":777,"pscid":85,"selected":0,"sellerid":7,"subhead":"滿2件,總價打6.50折","title":"Gap男裝 休閑舒適簡約水洗五袋直筒長褲緊身牛仔褲941825 深灰色 33/32(175/84A)"}],"sellerName":"商家7","sellerid":"7"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":12,"pid":1,"price":118,"pscid":1,"selected":0,"sellerid":17,"subhead":"每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下","title":"北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g"}],"sellerName":"商家17","sellerid":"17"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":4,"pid":2,"price":299,"pscid":1,"selected":0,"sellerid":18,"subhead":"每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下","title":"北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g"}],"sellerName":"商家18","sellerid":"18"},{"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":76,"price":37999.99,"pscid":40,"selected":0,"sellerid":20,"subhead":"購買電腦辦公部分商品滿1元返火車票5元優惠券(返完即止)","title":"全球購 新款Apple MacBook Pro 蘋果筆記本電腦 銀色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家20","sellerid":"20"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":5,"price":88.99,"pscid":1,"selected":0,"sellerid":21,"subhead":"每個中秋都不能簡單,無論身在何處,你總需要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下","title":"北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g"}],"sellerName":"商家21","sellerid":"21"}] */ private String msg; private String code; private List<DataBean> data; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } public static class DataBean { /** * list : [{"bargainPrice":22.9,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/2542855.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t1930/284/2865629620/390243/e3ade9c4/56f0a08fNbd3a1235.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2137/336/2802996626/155915/e5e90d7a/56f0a09cN33e01bd0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t1882/31/2772215910/389956/c8dbf370/56f0a0a2Na0c86ea6.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2620/166/2703833710/312660/531aa913/57709035N33857877.jpg!q70.jpg","num":1,"pid":24,"price":288,"pscid":2,"selected":0,"sellerid":1,"subhead":"三只松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》","title":"三只松鼠 堅果炒貨 零食奶油味 碧根果225g/袋"},{"bargainPrice":11800,"createtime":"2017-10-10T17:33:37","detailUrl":"https://item.m.jd.com/product/4338107.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6700/155/2098998076/156185/6cf95035/595dd5a5Nc3a7dab5.jpg!q70.jpg","num":2,"pid":57,"price":5199,"pscid":40,"selected":0,"sellerid":1,"subhead":"【i5 MX150 2G顯存】全高清窄邊框 8G內存 256固態硬盤 支持指紋識別 預裝WIN10系統","title":"小米(MI)Air 13.3英寸全金屬輕薄筆記本(i5-7200U 8G 256G PCle SSD MX150 2G獨顯 FHD 指紋識別 Win10)銀\r\n"},{"bargainPrice":99,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/4345173.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6037/35/2944615848/95178/6cd6cff0/594a3a10Na4ec7f39.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6607/258/1025744923/75738/da120a2d/594a3a12Ne3e6bc56.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6370/292/1057025420/64655/f87644e3/594a3a12N5b900606.jpg!q70.jpg","num":1,"pid":45,"price":2999,"pscid":39,"selected":0,"sellerid":1,"subhead":"高清雙攝,就是清晰!2000+1600萬高清攝像頭,6GB大內存+高通驍龍835處理器,性能怪獸!","title":"一加手機5 (A5000) 6GB+64GB 月巖灰 全網通 雙卡雙待 移動聯通電信4G手機"}] * sellerName : 商家1 * sellerid : 1 */ private String sellerName; private String sellerid; private List<ListBean> list; private boolean check; public boolean isCheck() { return check; } public void setCheck(boolean check) { this.check = check; } public String getSellerName() { return sellerName; } public void setSellerName(String sellerName) { this.sellerName = sellerName; } public String getSellerid() { return sellerid; } public void setSellerid(String sellerid) { this.sellerid = sellerid; } public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class ListBean { /** * bargainPrice : 22.9 * createtime : 2017-10-14T21:48:08 * detailUrl : https://item.m.jd.com/product/2542855.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends * images : https://m.360buyimg.com/n0/jfs/t1930/284/2865629620/390243/e3ade9c4/56f0a08fNbd3a1235.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2137/336/2802996626/155915/e5e90d7a/56f0a09cN33e01bd0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t1882/31/2772215910/389956/c8dbf370/56f0a0a2Na0c86ea6.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2620/166/2703833710/312660/531aa913/57709035N33857877.jpg!q70.jpg * num : 1 * pid : 24 * price : 288.0 * pscid : 2 * selected : 0 * sellerid : 1 * subhead : 三只松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》 * title : 三只松鼠 堅果炒貨 零食奶油味 碧根果225g/袋 */ 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 int cou=1; public int getCou() { return cou; } public void setCou(int cou) { this.cou = cou; } private boolean check; public boolean isCheck() { return check; } public void setCheck(boolean check) { this.check = check; } public double getBargainPrice() { return bargainPrice; } public void setBargainPrice(double bargainPrice) { this.bargainPrice = bargainPrice; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public String getDetailUrl() { return detailUrl; } public void setDetailUrl(String detailUrl) { this.detailUrl = detailUrl; } public String getImages() { return images; } public void setImages(String images) { this.images = images; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public 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; } } } }
app
public class MyApp extends Application{ @Override public void onCreate() { super.onCreate(); Fresco.initialize(this); } }
view層
先寫兩個接口
public interface ICart { void showlist(List<CartBean.DataBean> grouplist, List<List<CartBean.DataBean.ListBean>> childlist); }
public interface IView<T> { void showBean(T t); void showStr(String s); }
主頁面布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.bwie.zhangzhen20170108.MainActivity"> <ExpandableListView android:id="@+id/elv" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:layout_weight="9" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <CheckBox android:id="@+id/quanxuan" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text="全選" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:layout_marginLeft="50dp" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/zongjia" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="總價:0.0" /> <TextView android:text="共0件商品" android:id="@+id/tv_count" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <TextView android:text="去結算" android:background="#FFD82020" android:layout_marginLeft="100dp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout>
主頁面
public class MainActivity extends AppCompatActivity implements ICart { private ExpandableListView mElv; private CheckBox mQuanxuan; private TextView mZongjia; private TextView mTvCount; private MyExpandableAdapter myExpandableAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); new CartPresenter(this).getCart(); EventBus.getDefault().register(this); mQuanxuan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myExpandableAdapter.qx(mQuanxuan.isChecked()); } }); } private void initView() { mElv = (ExpandableListView) findViewById(R.id.elv); mQuanxuan = (CheckBox) findViewById(R.id.quanxuan); mZongjia = (TextView) findViewById(R.id.zongjia); mTvCount = (TextView) findViewById(R.id.tv_count); } @Override public void showlist(List<CartBean.DataBean> grouplist, List<List<CartBean.DataBean.ListBean>> childlist) { myExpandableAdapter = new MyExpandableAdapter(grouplist, this,childlist); mElv.setAdapter(myExpandableAdapter); for (int i = 0; i <grouplist.size() ; i++) { mElv.expandGroup(i); } } //接收傳過來的值 @Subscribe public void onPriceAndCount(CountAndPrice cp){ mZongjia.setText("共"+cp.getCount()+"件商品"); mTvCount.setText("總計:"+cp.getPrice()); } //接收傳過來的值 @Subscribe public void onPriceAndCount1(MessgeEvent event){ //改變全選的狀態 mQuanxuan.setChecked(event.isCheck()); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }
第二個頁面布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id="@+id/activity_add" tools:context="com.bwie.zhangzhen20170108.AddActivity"> <com.facebook.drawee.view.SimpleDraweeView android:layout_width="300dp" android:id="@+id/xqsdv1" android:layout_gravity="center" android:layout_height="300dp" /> <TextView android:id="@+id/tvtitle1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/tiaozhuan1" android:layout_weight="1" android:text="跳轉到購物車" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/tianjia1" android:layout_weight="1" android:text="添加到購物車" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout>
實現購物車的代碼
public class AddActivity extends AppCompatActivity implements View.OnClickListener,IView { private SimpleDraweeView mXqsdv; private TextView mTvtitle; private Button mTiaozhuan; private Button mTianjia; private LinearLayout mAddActivity; private XQPresenter xqPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); initView(); xqPresenter=new XQPresenter(this); xqPresenter.getXQ(); } private void initView() { mXqsdv = (SimpleDraweeView) findViewById(R.id.xqsdv1); mTvtitle = (TextView) findViewById(R.id.tvtitle1); mTiaozhuan = (Button) findViewById(R.id.tiaozhuan1); mTiaozhuan.setOnClickListener(this); mTianjia = (Button) findViewById(R.id.tianjia1); mTianjia.setOnClickListener(this); mAddActivity = (LinearLayout) findViewById(R.id.activity_add); } @Override public void onClick(View v) { switch (v.getId()) { default: break; //跳到MainActivity (購物車) case R.id.tiaozhuan1: startActivity(new Intent(this,MainActivity.class)); break; case R.id.tianjia1: xqPresenter.getAdd(); break; } } @Override public void showBean(Object o) { XQBean xqBean = (XQBean) o; XQBean.DataBean data = xqBean.getData(); String s = data.getImages().split("\\|")[0]; Uri uri =Uri.parse(s);//地址轉換成URI mXqsdv.setImageURI(uri); mTvtitle.setText(data.getTitle()+"\n"+data.getPrice()); } @Override public void showStr(String s) { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); } }
eventbus包
設置一個數量和價格的類
public class CountAndPrice { private int count ; private int price; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }
EventBus
public class MessgeEvent { private boolean check; public boolean isCheck() { return check; } public void setCheck(boolean check) { this.check = check; } }
model
實現詳情頁model層的接口
public interface IXQModel { public void getXQ(int pid, String str, final OnNetLisenter<XQBean> cgsb); }
實現詳情頁model
public class XQModel implements IXQModel{ @Override public void getXQ(int pid, String str, final OnNetLisenter<XQBean> onNetLisenter) { Flowable<XQBean> flowable = RetrofitHepler.getSerViceAPI().getXQ(pid, str); flowable.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Consumer<XQBean>() { @Override public void accept(XQBean xqBean) throws Exception { onNetLisenter.Success(xqBean); } }); } public void getAdd(int uid, int pid, String str, final OnNetLisenter<AddCart> onNetLisenter){ Flowable<AddCart> flowable = RetrofitHepler.getSerViceAPI().getMsg(uid, pid, str); flowable.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Consumer<AddCart>() { @Override public void accept(AddCart addCart) throws Exception { onNetLisenter.Success(addCart); } }); } }
購物車的model
public class CartModel { public void getCart(int uid, String str, final OnNetLisenter<CartBean> onNetLisenter){ Flowable<CartBean> flowable = RetrofitHepler.getSerViceAPI().getCart(uid,str); flowable.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Consumer<CartBean>() { @Override public void accept(CartBean cartBean) throws Exception { onNetLisenter.Success(cartBean); } }); } }
presenter層
詳情頁的P層
public class XQPresenter { private final XQModel xqModel; private IView iView; public XQPresenter(IView iView) { xqModel = new XQModel(); this.iView=iView; } public void getXQ(){ xqModel.getXQ(12, "android", new OnNetLisenter<XQBean>() { @Override public void Success(XQBean xqBean) { iView.showBean(xqBean); } }); } public void getAdd(){ xqModel.getAdd(3043, 12, "android", new OnNetLisenter<AddCart>() { @Override public void Success(AddCart addCart) { iView.showStr(addCart.getMsg()); } }); } }
購物車的P層
public class CartPresenter { private ICart iCart; private final CartModel cartModel; public CartPresenter(ICart iCart) { this.iCart = iCart; cartModel = new CartModel(); } public void getCart(){ cartModel.getCart(3043,"android",new OnNetLisenter<CartBean>(){ @Override public void Success(CartBean cartBean) { List<CartBean.DataBean> grouplist = cartBean.getData(); List<List<CartBean.DataBean.ListBean>> childlist = new ArrayList<>(); for (int i = 0; i < grouplist.size(); i++) { CartBean.DataBean dataBean = grouplist.get(i); List<CartBean.DataBean.ListBean> list = dataBean.getList(); childlist.add(list); } iCart.showlist(grouplist,childlist); } }); } }
adapter
public class MyExpandableAdapter extends BaseExpandableListAdapter { private List<CartBean.DataBean> groupdata; private Context context; private List<List<CartBean.DataBean.ListBean>> childlist; public MyExpandableAdapter( List<CartBean.DataBean> groupdata, Context context, List<List<CartBean.DataBean.ListBean>> childlist) { this.groupdata = groupdata; this.context = context; this.childlist = childlist; } @Override public int getGroupCount() { return groupdata.size(); } @Override public int getChildrenCount(int groupPosition) { return childlist.get(groupPosition).size(); } @Override public Object getGroup(int groupPosition) { return groupdata.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return null; } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return false; } @Override public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { final GroupViewHolder holder; if (convertView == null) { convertView = View.inflate(context, R.layout.group_item, null); holder = new GroupViewHolder(); holder.tv_group = (TextView) convertView.findViewById(R.id.tv_group); holder.group_cb = (CheckBox) convertView.findViewById(R.id.gx_group); convertView.setTag(holder); } else { holder = (GroupViewHolder) convertView.getTag(); } final CartBean.DataBean dataBean = groupdata.get(groupPosition); String sellerName = dataBean.getSellerName(); holder.group_cb.setChecked(dataBean.isCheck()); //點擊一級checkbox的狀態 holder.group_cb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dataBean.setCheck(holder.group_cb.isChecked()); //改變所有孩子的狀態 changeChildState(groupPosition,holder.group_cb.isChecked()); EventBus.getDefault().post(jS()); //通過判斷一級的checkbox判斷全選的狀態 changeMianQXstatus(checkGroupAll()); notifyDataSetChanged(); } }); return convertView; } @Override public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final ChildViewHolder holder; if (convertView == null) { convertView = View.inflate(context, R.layout.child_item, null); holder = new ChildViewHolder(); holder.tv_title= (TextView) convertView.findViewById(R.id.title); holder.price= (TextView) convertView.findViewById(R.id.price); holder.child_cb= (CheckBox) convertView.findViewById(R.id.gouxuan_child); holder.add= (TextView) convertView.findViewById(R.id.jia); holder.del= (TextView) convertView.findViewById(R.id.del); holder.jian= (TextView) convertView.findViewById(R.id.jian); holder.sdv= (SimpleDraweeView) convertView.findViewById(R.id.title_img); holder.tv_num= (TextView) convertView.findViewById(R.id.tv_num); holder.yanse= (TextView) convertView.findViewById(R.id.yanse); convertView.setTag(holder); } else { holder = (ChildViewHolder) convertView.getTag(); } final CartBean.DataBean.ListBean listBean = childlist.get(groupPosition).get(childPosition); int price = (int) listBean.getPrice(); holder.child_cb.setChecked(listBean.isCheck()); holder.price.setText("¥:"+price+""); String title = listBean.getTitle(); holder.tv_title.setText(title); String subhead = listBean.getSubhead(); String substring = subhead.substring(1, 10)+"....."; holder.yanse.setText(substring); String images = listBean.getImages(); String[] split = images.split("\\|"); String s = split[0]; Uri uri=Uri.parse(s); holder.sdv.setImageURI(uri); // listBean.setCou(Integer.parseInt(holder.tv_num.getText().toString())); //給子條目的checkBox點擊事件 holder.child_cb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listBean.setCheck(holder.child_cb.isChecked()); EventBus.getDefault().post(jS()); //如果二級的checkBox選中,就讓一級的checkBox勾選 if(holder.child_cb.isChecked()) { if (ischeckAllchild(groupPosition)) { //改變一級checkBox的狀態 changeGroupstatus(groupPosition,true); //通過判斷一級的CheckBox的狀態來改變全選的狀態 changeMianQXstatus(checkGroupAll()); } }else{ changeGroupstatus(groupPosition,false); changeMianQXstatus(checkGroupAll()); } notifyDataSetChanged(); } }); //點擊加加的功能 holder.add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int cou = listBean.getCou(); holder.tv_num.setText(++cou+""); listBean.setCou(cou); if(holder.child_cb.isChecked()){ EventBus.getDefault().post(jS()); } } }); //點擊減減的功能 holder.jian.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int cou = listBean.getCou(); if(cou==1) { Toast.makeText(context, "最小數量為1", Toast.LENGTH_SHORT).show(); return;} holder.tv_num.setText(--cou+""); listBean.setCou(cou); if (holder.child_cb.isChecked()) { EventBus.getDefault().post(jS()); } } }); //點擊刪除 holder.del.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<CartBean.DataBean.ListBean> listBeen = childlist.get(groupPosition); CartBean.DataBean.ListBean remove = listBeen.remove(childPosition); if(listBeen.size()==0){ childlist.remove(childPosition); groupdata.remove(groupPosition); } EventBus.getDefault().post(jS()); notifyDataSetChanged(); } }); return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } class GroupViewHolder { CheckBox group_cb; TextView tv_group; } class ChildViewHolder { CheckBox child_cb; TextView tv_title,price,yanse,tv_num; TextView del,add,jian; SimpleDraweeView sdv; } /** * 判斷全部的二級是CheckBox否選中 * */ private boolean ischeckAllchild(int g){ List<CartBean.DataBean.ListBean> listBeen = childlist.get(g); for (int i = 0; i <listBeen.size() ; i++) { CartBean.DataBean.ListBean listBean = listBeen.get(i); if(!listBean.isCheck()){ return false; } } return true; } /** * 計算數量和價格 * 通過遍歷一級的得到二級的CheckBox,如果是選擇的選中狀態的話,就統計它們的總計的數量和價格 */ private CountAndPrice jS(){ int cou=0; int jiage=0; for (int i = 0; i <groupdata.size() ; i++) { for (int j = 0; j <childlist.get(i).size() ; j++) { CartBean.DataBean.ListBean listBean = childlist.get(i).get(j); if(listBean.isCheck()){ cou+=listBean.getCou(); jiage+=(int)listBean.getPrice()*listBean.getCou(); } } } CountAndPrice countAndPrice = new CountAndPrice(); countAndPrice.setCount(cou); countAndPrice.setPrice(jiage); return countAndPrice; } /** * 改變一級列表的狀態 */ private void changeGroupstatus(int groupPosition,boolean flag ){ CartBean.DataBean dataBean = groupdata.get(groupPosition); dataBean.setCheck(flag); } /** * 改變全選的狀態 * */ private void changeMianQXstatus(boolean flag){ MessgeEvent messgeEvent = new MessgeEvent(); messgeEvent.setCheck(flag); EventBus.getDefault().post(messgeEvent); } /** * 判斷一級的是否全部選中 */ private boolean checkGroupAll(){ for (int i = 0; i < groupdata.size(); i++) { if(!groupdata.get(i).isCheck()){ return false; } } return true; } /** * 改變所有孩子的狀態 */ private void changeChildState(int grouPistion,boolean flag){ List<CartBean.DataBean.ListBean> listBeen = childlist.get(grouPistion); for (int i = 0; i < listBeen.size(); i++) { listBeen.get(i).setCheck(flag); } } /** * 改變全選的 */ public void qx(boolean flag){ for (int i = 0; i < groupdata.size(); i++) { changeGroupstatus(i, flag); changeChildState(i, flag); } EventBus.getDefault().post(jS()); notifyDataSetChanged(); } }
group_item.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:orientation="horizontal"> <CheckBox android:id="@+id/gx_group" android:focusable="false" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/tv_group" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
child_item.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:orientation="vertical"> <TextView android:id="@+id/title" android:layout_marginLeft="20dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <CheckBox android:layout_marginLeft="20dp" android:gravity="center_vertical" android:id="@+id/gouxuan_child" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <com.facebook.drawee.view.SimpleDraweeView android:gravity="center_vertical" android:id="@+id/title_img" android:layout_width="50dp" android:layout_height="50dp" /> <LinearLayout android:orientation="vertical" android:layout_marginLeft="30dp" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/price" android:layout_marginLeft="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/yanse" android:layout_marginLeft="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:layout_marginLeft="100dp" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/jian" android:layout_width="20dp" android:layout_height="20dp" android:textSize="15sp" android:text="一"/> <TextView android:id="@+id/tv_num" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:paddingBottom="2dp" android:paddingLeft="20dp" android:paddingRight="20dp" android:paddingTop="2dp" android:text="1" /> <TextView android:id="@+id/jia" android:layout_width="20dp" android:layout_height="20dp" android:layout_marginLeft="5dp" android:text="+" android:textSize="15sp"/> </LinearLayout> </LinearLayout> <TextView android:id="@+id/del" android:layout_marginLeft="20dp" android:text="刪除" android:textColor="#FFFFFF" android:background="#ff3660" android:layout_width="32dp" android:layout_height="29dp" /> </LinearLayout> </LinearLayout>
上述內容就是怎么在RxJava中使用Retrofit和Mvp實現購物車,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。