MVP+Retrofit+RxJAVA实现购物车

xiaoxiao2021-02-28  22

compile 'com.squareup.okhttp3:okhttp:3.9.0' compile 'com.google.code.gson:gson:2.8.2' compile 'com.android.support:recyclerview-v7:25.3.1' compile 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' compile 'com.facebook.fresco:fresco:0.14.1' compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' compile'com.squareup.retrofit2:converter-gson:2.0.0-beta4' compile 'com.squareup.retrofit2:converter-scalars:2.0.0' compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0' compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

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

布局:

activity_main

<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.example.lenovo.goshopp_text_4_23.MainActivity"> <RelativeLayout android:padding="10dp" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:textSize="23sp" android:layout_centerVertical="true" android:text="GO" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:textStyle="bold" android:textSize="23sp" android:layout_centerHorizontal="true" android:text="购物车" android:textColor="@color/colorAccent" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/bianji" android:textSize="20sp" android:layout_centerVertical="true" android:layout_alignParentRight="true" android:text="编辑" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> <TextView android:layout_marginTop="5dp" android:layout_width="match_parent" android:layout_height="1dp" android:background="#D4D4D4"/> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_View" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <RelativeLayout android:gravity="center_vertical" android:orientation="horizontal" android:layout_alignParentBottom="true" android:layout_width="match_parent" android:layout_height="wrap_content"> <CheckBox android:layout_marginLeft="10dp" android:layout_centerVertical="true" android:background="@drawable/noxuanzhongx" android:button="@null" android:id="@+id/quanxuan" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_centerVertical="true" android:textStyle="bold" android:layout_marginLeft="40dp" android:textSize="23sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="全选" /> <LinearLayout android:orientation="vertical" android:layout_centerInParent="true" android:layout_marginRight="70dp" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:textColor="#e53e42" android:id="@+id/total_price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:text="总价 : ¥0" /> <TextView android:layout_alignBottom="@+id/total_price" android:id="@+id/total_num" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:text="0件商品" /> </LinearLayout> <TextView android:id="@+id/quzhifu" android:layout_centerVertical="true" android:layout_alignParentRight="true" android:padding="20dp" android:gravity="center" android:textSize="15sp" android:text="去支付" android:textColor="#fff" android:background="#FC7903" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:id="@+id/linear_shanchu" android:visibility="gone" android:layout_alignParentRight="true" android:layout_marginLeft="10dp" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:paddingRight="10dp" android:paddingLeft="10dp" android:padding="10dp" android:gravity="center" android:textSize="10sp" android:text="分享宝贝" android:textColor="#fff" android:background="#FC7903" android:layout_width="wrap_content" android:layout_height="match_parent" /> <TextView android:paddingRight="10dp" android:paddingLeft="10dp" android:padding="10dp" android:gravity="center" android:textSize="10sp" android:text="移到收藏夹" android:textColor="#fff" android:background="#FC7903" android:layout_width="wrap_content" android:layout_height="match_parent" /> <TextView android:id="@+id/shanchu" android:paddingRight="10dp" android:paddingLeft="10dp" android:padding="10dp" android:gravity="center" android:textSize="10sp" android:text="删除" android:textColor="#fff" android:background="#DC143C" android:layout_width="wrap_content" android:layout_height="match_parent" /> </LinearLayout> </RelativeLayout> </LinearLayout>

custom_jiajian

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="horizontal" android:gravity="center_vertical" android:layout_height="match_parent"> <Button android:background="#F2F1F1" android:textSize="20sp" android:id="@+id/reverse" android:text="" android:layout_width="40dp" android:layout_height="40dp" /> <EditText android:gravity="center" android:background="#FAFAFA" android:textStyle="bold" android:textSize="23sp" android:layout_width="40dp" android:layout_height="40dp" android:text="1" android:id="@+id/count" /> <Button android:id="@+id/add" android:background="#F2F1F1" android:textSize="25sp" android:text="+" android:layout_width="40dp" android:layout_height="40dp" /> </LinearLayout>

recy_cart_item

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:fresco="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent"> <RelativeLayout android:padding="5dp" android:background="#FFFFFF" android:layout_width="match_parent" android:layout_height="wrap_content"> <CheckBox android:layout_centerVertical="true" android:id="@+id/shop_checkbox" android:layout_width="50dp" android:layout_height="50dp" /> <TextView android:layout_centerVertical="true" android:layout_marginLeft="35dp" android:text="良品铺子" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="23sp" android:textStyle="bold" android:id="@+id/shop_name" /> <TextView android:id="@+id/item_bianji" android:layout_centerVertical="true" android:layout_alignParentRight="true" android:textSize="20sp" android:text="编辑" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:background="#D4D4D4"/> <LinearLayout android:background="#F2F2F2" android:gravity="center_vertical" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <CheckBox android:id="@+id/item_checkbox" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <com.facebook.drawee.view.SimpleDraweeView fresco:failureImage="@mipmap/ic_launcher" fresco:placeholderImage="@mipmap/ic_launcher" android:id="@+id/item_face" android:src="@mipmap/ic_launcher" android:layout_width="140dp" android:layout_height="140dp" /> <LinearLayout android:layout_marginLeft="10dp" android:orientation="vertical" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content"> <TextView android:id="@+id/item_name" android:textSize="20sp" android:text="三只松鼠" android:layout_width="wrap_content" android:layout_weight="1" android:layout_height="0dp" /> <TextView android:textColor="#f00" android:id="@+id/item_price" android:textSize="23sp" android:text="299" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" /> <com.example.lenovo.goshopp_text_4_23.CustomJiaJian android:visibility="gone" android:id="@+id/custom_jiajian" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" /> <TextView android:textSize="20sp" android:visibility="gone" android:id="@+id/item_yansechima" android:text="颜色 : 黑色 ; 尺码: 29" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <!-- <ImageView android:visibility="gone" android:id="@+id/item_delete" android:layout_marginRight="10dp" android:src="@drawable/shopcart_delete" android:layout_width="30dp" android:layout_height="30dp" />--> <TextView android:visibility="gone" android:id="@+id/item_delete" android:padding="20dp" android:background="#FC7903" android:textColor="#fff" android:textSize="23sp" android:gravity="center" android:text="删除" android:layout_width="wrap_content" android:layout_height="match_parent" /> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:background="#D4D4D4"/> </LinearLayout>

MyViewCallBackpublic interface MyViewCallBack { public void success(CartBean cartBean); public void failure(); } public interface MyViewCallBack2 { public void success(DeleteBean deleteBean); public void failure(); } public interface MyModelCallBack { public void success(CartBean cartBean); public void failure(); } public interface MyModelCallBack2 { public void success(DeleteBean deleteBean); public void failure(); }

public interface IGetService { //查询购物车, //http://120.27.23.105/product/getCarts?source=android&uid=1650 @GET Observable<String> select(@Url String url, @QueryMap Map<String,String> map); //删除购物车 // http://120.27.23.105/product/deleteCart?uid=1650&pid=1 @GET Observable<String> delete(@Url String url, @QueryMap Map<String,String> map); //更新购物车 // "token": "2FC3EF31EA25696D2715A971ADE38DE1", //https://www.zhaoapi.cn/product/updateCarts?uid=1650&sellerid=1&pid=1&selected=0&num=10&token=2FC3EF31EA25696D2715A971ADE38DE1 @GET Observable<String> update(@Url String url,@QueryMap Map<String,String> map); }

AbstractObserver

public abstract class AbstractObserver<T> implements Observer<String> { //不需要下面重写的四个方法,只需要自己写的两个抽象方法 public abstract void onSuccess(T t); public abstract void onFailure(); @Override public void onSubscribe(Disposable d) { } @Override public void onNext(String result) { //这里的s是请求网络传回来的string字符串 Type type = getClass().getGenericSuperclass(); Type[] types = ((ParameterizedType) type).getActualTypeArguments(); Class clazz = (Class) types[0];//强转成类对象 //使用gson解析 Gson gson = new Gson(); T t = (T) gson.fromJson(result,clazz); //调用抽象方法onSuccess onSuccess(t); } @Override public void onError(Throwable e) { try { onFailure(); }catch (Exception e1){ e.printStackTrace(); } } @Override public void onComplete() { } }

APIFactory

public class APIFactory { private static APIFactory factory = null; public static APIFactory getInstance(){ if(factory==null){ synchronized (APIFactory.class){ if(factory==null){ factory = new APIFactory(); } } } return factory; } //查询购物车的方法 public void select(String url, Map<String,String> map, Observer<String> observer){ //调用retrofit工具类 RetrofitUtils.getInstance().select(url,map) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(observer); } //删除购物车的方法 public void delete(String url, Map<String,String> map, Observer<String> observer){ //调用retrofit工具类 RetrofitUtils.getInstance().select(url,map) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(observer); } }

OkHttpUtils

public class OkHttpUtils { private static OkHttpClient client = null; public static OkHttpClient getInstance(){ if(client==null){ synchronized (OkHttpUtils.class){ if(client==null){ client = new OkHttpClient.Builder() .connectTimeout(2000, TimeUnit.SECONDS) .writeTimeout(2000,TimeUnit.SECONDS) .readTimeout(2000,TimeUnit.SECONDS) .build(); } } } return client; } }

RetrofitUtils

public class RetrofitUtils { private static IGetService service = null; //http://api.tianapi.com/nba/?key=71e58b5b2f930eaf1f937407acde08fe&num=10 //单例模式 public static IGetService getInstance(){ if(service==null){ synchronized (RetrofitUtils.class){ if(service==null){ Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://120.27.23.105") .addConverterFactory(ScalarsConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(OkHttpUtils.getInstance()) .build(); service = retrofit.create(IGetService.class); } } } return service; } }

MyModel

public class MyModel { public void select(final MyModelCallBack myModelCallBack) { final Map<String,String> map = new HashMap<>(); map.put("source","android"); map.put("uid","1650"); //调用apifactory里面的方法 APIFactory.getInstance().select("/product/getCarts", map, new AbstractObserver<CartBean>() { @Override public void onSuccess(CartBean cartBean) { myModelCallBack.success(cartBean); } @Override public void onFailure() { myModelCallBack.failure(); } }); } }

MyModel2

public class MyModel2 { public void delete(String pid,final MyModelCallBack2 myModelCallBack2) { final Map<String,String> map = new HashMap<>(); map.put("source","android"); map.put("pid",pid); map.put("uid","1650"); //调用apifactory里面的方法 APIFactory.getInstance().delete("/product/deleteCart", map, new AbstractObserver<DeleteBean>() { @Override public void onSuccess(DeleteBean deleteBean) { myModelCallBack2.success(deleteBean); } @Override public void onFailure() { myModelCallBack2.failure(); } }); } }

MyPresenter

public class MyPresenter { MyModel myModel; MyViewCallBack myViewCallBack; public MyPresenter(MyViewCallBack myViewCallBack) { this.myViewCallBack = myViewCallBack; this.myModel = new MyModel(); } public void select() { myModel.select(new MyModelCallBack() { @Override public void success(CartBean cartBean) { myViewCallBack.success(cartBean); } @Override public void failure() { myViewCallBack.failure(); } }); } public void detach() { this.myViewCallBack = null; } }

MyPresenter2

public class MyPresenter2 { MyModel2 myModel2; MyViewCallBack2 myViewCallBack2; public MyPresenter2(MyViewCallBack2 myViewCallBack2) { this.myViewCallBack2 = myViewCallBack2; this.myModel2 = new MyModel2(); } public void delete(String pid) { myModel2.delete(pid,new MyModelCallBack2() { @Override public void success(DeleteBean deleteBean) { myViewCallBack2.success(deleteBean); } @Override public void failure() { myViewCallBack2.failure(); } }); } public void detach() { this.myViewCallBack2 = null; } }

public class CartBean { 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-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":1,"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"}] * sellerName : 商家1 * sellerid : 1 */ 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 { /** * bargainPrice : 11800.0 * 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 : 1 * pid : 57 * price : 5199.0 * 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)银 */ private int isFirst = 1;//1为显示商�? private boolean item_check;//每个商品的选中状�? private boolean shop_check;//商店的选中状�? public int getIsFirst() { return isFirst; } public void setIsFirst(int isFirst) { this.isFirst = isFirst; } public boolean isItem_check() { return item_check; } public void setItem_check(boolean item_check) { this.item_check = item_check; } public boolean isShop_check() { return shop_check; } public void setShop_check(boolean shop_check) { this.shop_check = shop_check; } 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; } } } }

public class DeleteBean { /** * msg : 购物车数据不存在 * code : 1 */ 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; } }

CustomJiaJian

public class CustomJiaJian extends LinearLayout { private Button reverse; private Button add; private EditText countEdit; private int mCount =1; public CustomJiaJian(Context context) { super(context); } public CustomJiaJian(final Context context, @Nullable AttributeSet attrs) { super(context, attrs); View view = View.inflate(context, R.layout.custom_jiajian,this); reverse = (Button) view.findViewById(R.id.reverse); add = (Button) view.findViewById(R.id.add); countEdit = (EditText) view.findViewById(R.id.count); reverse.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String content = countEdit.getText().toString().trim(); int count = Integer.valueOf(content); if(count>1){ mCount = count-1; countEdit.setText(mCount+""); //回调给adapter里面 if(customListener!=null){ customListener.jiajian(mCount); } }else{ Toast.makeText(context, "最小数量为1", Toast.LENGTH_SHORT).show(); } } }); add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String content = countEdit.getText().toString().trim(); int count = Integer.valueOf(content)+1; mCount = count; countEdit.setText(mCount+""); //接口回调给adapter if(customListener!=null){ customListener.jiajian(mCount); } } }); } public CustomJiaJian(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } CustomListener customListener; public void setCustomListener(CustomListener customListener){ this.customListener = customListener; } //加减的接口 public interface CustomListener{ public void jiajian(int count); public void shuRuZhi(int count); } public void setEditText(int num) { if(countEdit!=null){ countEdit.setText(num+""); } } }

MainActivity

public class MainActivity extends AppCompatActivity implements MyViewCallBack{ private RecyclerView recyclerView; private TextView total_price; private TextView total_num; private CheckBox quanxuan; private MyPresenter myPresenter; private RecyAdapter recyAdapter; private TextView bianji; private LinearLayout linear_shanchu; private TextView quzhifu; private TextView shanchu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = (RecyclerView) findViewById(R.id.recycler_View); total_price = (TextView) findViewById(R.id.total_price); total_num = (TextView) findViewById(R.id.total_num); quanxuan = (CheckBox) findViewById(R.id.quanxuan); bianji = findViewById(R.id.bianji); linear_shanchu = findViewById(R.id.linear_shanchu); quzhifu = findViewById(R.id.quzhifu); shanchu = findViewById(R.id.shanchu); bianji.setTag(1);//编辑设置tag quanxuan.setTag(1);//1为不选中 LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false); myPresenter = new MyPresenter(this); recyAdapter = new RecyAdapter(this); //进入页面查询购物车的数据 myPresenter.select(); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(recyAdapter); //调用recyAdapter里面的接口,设置 全选按钮 总价 总数量 recyAdapter.setUpdateListener(new RecyAdapter.UpdateListener() { @Override public void setTotal(String total, String num, boolean allCheck) { //设置ui的改变 total_num.setText(""+num+"件商品");//总数量 total_price.setText("总价 :¥"+total+"");//总价 if(allCheck){ quanxuan.setTag(2); quanxuan.setBackgroundResource(R.drawable.xuanzhong); }else{ quanxuan.setTag(1); quanxuan.setBackgroundResource(R.drawable.noxuanzhongx); } quanxuan.setChecked(allCheck); } }); //这里只做ui更改, 点击全选按钮,,调到adapter里面操作 quanxuan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //调用adapter里面的方法 ,,把当前quanxuan状态传递过去 int tag = (int) quanxuan.getTag(); if(tag==1){ quanxuan.setTag(2); quanxuan.setBackgroundResource(R.drawable.xuanzhong); }else{ quanxuan.setTag(1); quanxuan.setBackgroundResource(R.drawable.noxuanzhongx ); } recyAdapter.quanXuan(quanxuan.isChecked()); } }); //点击批量删除的按钮 shanchu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { recyAdapter.shanChu(); } }); //点击编辑按钮, bianji.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int tag = (int) bianji.getTag(); if(tag==1){ bianji.setText("完成"); bianji.setTag(2); quzhifu.setVisibility(View.GONE); linear_shanchu.setVisibility(View.VISIBLE); }else{ bianji.setText("编辑"); bianji.setTag(1); quzhifu.setVisibility(View.VISIBLE); linear_shanchu.setVisibility(View.GONE); } } }); } @Override public void success(CartBean cartBean) { if(cartBean!=null) { //System.out.println(cartBean.getData().get(0).getList().get(0).getTitle()); //将返回的数据 添加到适配器里 recyAdapter.add(cartBean); } } @Override public void failure() { System.out.println("网不好"); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "网有点慢", Toast.LENGTH_SHORT).show(); } }); } @Override protected void onDestroy() { super.onDestroy(); //调用p层的解除绑定 myPresenter.detach(); } }

RecyAdapter

public class RecyAdapter extends RecyclerView.Adapter<RecyAdapter.MyViewHolder> implements MyViewCallBack2,MyViewCallBack { MyPresenter myPresenter; //创建大的集合 private List<CartBean.DataBean.ListBean> list; //存放商家的id和商家的名称的map集合 private Map<String,String> map = new HashMap<>(); MyPresenter2 myPresenter2 ; Context context; public RecyAdapter(Context context) { this.context = context; myPresenter = new MyPresenter(this); myPresenter2 = new MyPresenter2(this); //初始化fresco Fresco.initialize(context); } public void add(CartBean cartBean) { if(list==null){ list = new ArrayList<>(); } if(cartBean!=null) { for (CartBean.DataBean shop : cartBean.getData()) { map.put(shop.getSellerid(), shop.getSellerName()); //第二层遍历里面的商品 for (int i = 0; i < shop.getList().size(); i++) { //添加到list集合里 list.add(shop.getList().get(i)); } } //调用方法 设置显示或隐藏 商铺名 setFirst(list); } notifyDataSetChanged(); } /** * 设置数据源,控制是否显示商家 * */ private void setFirst(List<CartBean.DataBean.ListBean> list) { if(list.size()>0){ list.get(0).setIsFirst(1); //从第二条开始遍历 for (int i=1;i<list.size();i++){ //如果和前一个商品是同一家商店的 if (list.get(i).getSellerid() == list.get(i-1).getSellerid()){ //设置成2不显示商铺 list.get(i).setIsFirst(2); }else{//设置成1显示商铺 list.get(i).setIsFirst(1); //如果当前条目选中,把当前的商铺也选中 if (list.get(i).isItem_check()==true){ list.get(i).setShop_check(list.get(i).isItem_check()); } } } } } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(context, R.layout.recy_cart_item,null); MyViewHolder myViewHolder = new MyViewHolder(view); return myViewHolder; } @Override public void onBindViewHolder(final MyViewHolder holder, final int position) { /** * 设置商铺的 shop_checkbox和商铺的名字 显示或隐藏 * */ if(list.get(position).getIsFirst()==1){ //显示商家 holder.shop_checkbox.setVisibility(View.VISIBLE); holder.shop_name.setVisibility(View.VISIBLE); //设置shop_checkbox的选中状态 holder.shop_checkbox.setChecked(list.get(position).isShop_check()); holder.shop_name.setText(map.get(String.valueOf(list.get(position).getSellerid()))+" "); }else{//2 //隐藏商家 holder.shop_name.setVisibility(View.GONE); holder.shop_checkbox.setVisibility(View.GONE); } //拆分images字段 String[] split = list.get(position).getImages().split("\\|"); //设置商品的图片 holder.item_face.setImageURI(Uri.parse(split[0])); // ImageLoader.getInstance().displayImage(split[0],holder.item_face); //控制商品的item_checkbox,,根据字段改变 holder.item_checkbox.setChecked(list.get(position).isItem_check()); holder.item_name.setText(list.get(position).getTitle()); holder.item_price.setText(list.get(position).getPrice()+""); //调用customjiajian里面的方法设置 加减号中间的数字 holder.customJiaJian.setEditText(list.get(position).getNum()); holder.item_bianji.setTag(1); //点击item编辑才显示 自定义加减框 holder.item_bianji.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int tag= (int) holder.item_bianji.getTag(); if(tag==1) { //加减号显示 holder.item_bianji.setText("完成"); holder.customJiaJian.setVisibility(View.VISIBLE); //商品的名称隐藏 holder.item_name.setVisibility(View.GONE); holder.item_yansechima.setVisibility(View.VISIBLE); holder.item_price.setVisibility(View.GONE); holder.item_delete.setVisibility(View.VISIBLE); holder.item_bianji.setTag(2); }else{ //相反的 隐藏的显示,显示的隐藏 //加减号显示 holder.item_bianji.setText("编辑"); holder.customJiaJian.setVisibility(View.GONE); //商品的名称隐藏 holder.item_name.setVisibility(View.VISIBLE); holder.item_yansechima.setVisibility(View.GONE); holder.item_price.setVisibility(View.VISIBLE); holder.item_delete.setVisibility(View.GONE); holder.item_bianji.setTag(1); } } }); //设置点击多选框 //商铺的shop_checkbox点击事件 ,控制商品的item_checkbox holder.shop_checkbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //先改变数据源中的shop_check list.get(position).setShop_check(holder.shop_checkbox.isChecked()); for (int i=0;i<list.size();i++){ //如果是同一家商铺的 都给成相同状态 if(list.get(position).getSellerid()==list.get(i).getSellerid()){ //当前条目的选中状态 设置成 当前商铺的选中状态 list.get(i).setItem_check(holder.shop_checkbox.isChecked()); } } //刷新适配器 notifyDataSetChanged(); //调用求和的方法 sum(list); } }); //商品的item_checkbox点击事件,控制商铺的shop_checkbox holder.item_checkbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //先改变数据源中的item_checkbox list.get(position).setItem_check(holder.item_checkbox.isChecked()); //反向控制商铺的shop_checkbox for (int i=0;i<list.size();i++){ for (int j=0;j<list.size();j++){ //如果两个商品是同一家店铺的 并且 这两个商品的item_checkbox选中状态不一样 if(list.get(i).getSellerid()==list.get(j).getSellerid() && !list.get(j).isItem_check()){ //就把商铺的shop_checkbox改成false list.get(i).setShop_check(false); break; }else{ //同一家商铺的商品 选中状态都一样,就把商铺shop_checkbox状态改成true list.get(i).setShop_check(true); } } } //更新适配器 notifyDataSetChanged(); //调用求和的方法 sum(list); } }); //删除条目的点击事件 holder.item_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { list.remove(position);//移除集合中的当前数据 //删除完当前的条目 重新判断商铺的显示隐藏 setFirst(list); //调用重新求和 sum(list); notifyDataSetChanged(); } }); //加减号的监听, holder.customJiaJian.setCustomListener(new CustomJiaJian.CustomListener() { @Override public void jiajian(int count) { //改变数据源中的数量 list.get(position).setNum(count); notifyDataSetChanged(); sum(list); } @Override //输入值 求总价 public void shuRuZhi(int count) { list.get(position).setNum(count); notifyDataSetChanged(); sum(list); } }); } //批量删除的按钮 public void shanChu() { //存储删除的id final List<Integer> delete_listid = new ArrayList<>(); for (int i=0;i<list.size();i++){ if(list.get(i).isItem_check()){ //将要删除的pid添加到这个集合里 delete_listid.add(list.get(i).getPid()); } } if (delete_listid.size()==0){ //如果没有要删除的,就吐司提示 Toast.makeText(context, "请选中至少一个商品后再删除", Toast.LENGTH_SHORT).show(); return; } //弹框 final AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setTitle("操作提示"); dialog.setMessage("你确定要删除这"+delete_listid.size()+"个商品?"); dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //使用接口删除 String a = ""; for(int j=0;j<delete_listid.size();j++) { // a+=delete_listid.get(j)+""; Integer integer = delete_listid.get(j); String pid = String.valueOf(integer); myPresenter2.delete(pid); // list.remove(j); } // Toast.makeText(context, a,Toast.LENGTH_SHORT).show(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); } }).create().show(); } //view层调用这个方法, 点击quanxuan按钮的操作 public void quanXuan(boolean checked) { for (int i=0;i<list.size();i++){ list.get(i).setShop_check(checked); list.get(i).setItem_check(checked); } notifyDataSetChanged(); sum(list); } private void sum(List<CartBean.DataBean.ListBean> list) { int totalNum = 0; float totalMoney = 0.0f; boolean allCheck = true; for (int i=0;i<list.size();i++){ if (list.get(i).isItem_check()){ totalNum += list.get(i).getNum(); totalMoney += list.get(i).getNum() * list.get(i).getPrice(); }else{ //如果有个未选中,就标记为false allCheck = false; } } //接口回调出去 把总价 总数量 和allcheck 传给view updateListener.setTotal(totalMoney+"",totalNum+"",allCheck); } @Override public int getItemCount() { return list==null?0:list.size(); } @Override public void success(DeleteBean deleteBean) { //调用第一个presenter的方法 重新查询数据 myPresenter.select(); } @Override public void success(CartBean cartBean) { list.clear(); add(cartBean); } @Override public void failure() { System.out.println("网不好"); Toast.makeText(context, "adapter网有点慢", Toast.LENGTH_SHORT).show(); } public static class MyViewHolder extends RecyclerView.ViewHolder{ private final CheckBox shop_checkbox; private final TextView shop_name; private final CheckBox item_checkbox; private final TextView item_name; private final TextView item_price; private final CustomJiaJian customJiaJian; //private final ImageView item_delete; private final TextView item_delete; private final ImageView item_face; private final TextView item_bianji; private final TextView item_yansechima; public MyViewHolder(View itemView) { super(itemView); //拿到控件 shop_checkbox = (CheckBox) itemView.findViewById(R.id.shop_checkbox); shop_name = (TextView) itemView.findViewById(R.id.shop_name); item_checkbox = (CheckBox) itemView.findViewById(R.id.item_checkbox); item_name = (TextView) itemView.findViewById(R.id.item_name); item_price = (TextView) itemView.findViewById(R.id.item_price); customJiaJian = (CustomJiaJian) itemView.findViewById(R.id.custom_jiajian); //item_delete = (ImageView) itemView.findViewById(R.id.item_delete); item_delete = (TextView) itemView.findViewById(R.id.item_delete); item_face = (ImageView) itemView.findViewById(R.id.item_face); item_bianji = itemView.findViewById(R.id.item_bianji); item_yansechima = itemView.findViewById(R.id.item_yansechima); } } UpdateListener updateListener; public void setUpdateListener(UpdateListener updateListener){ this.updateListener = updateListener; } //接口 public interface UpdateListener{ public void setTotal(String total,String num,boolean allCheck); }

}

转载请注明原文地址: https://www.6miu.com/read-1950266.html

最新回复(0)