购物车

 //依赖
    compile 'io.reactivex.rxjava2:rxjava:2.0.1'  //Rxjava
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'  //Rx安卓
    compile 'com.squareup.retrofit2:retrofit:2.3.0' //Retrofit请求网络
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'//Gson
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'//拦截器
    compile 'com.youth.banner:banner:1.4.9' //Banner依赖
    //图片的依赖
    compile 'com.facebook.fresco:fresco:0.14.1'
    compile 'com.facebook.fresco:animated-base-support:0.14.1'
    compile 'com.facebook.fresco:animated-gif:0.14.1'
    compile 'com.facebook.fresco:webpsupport:0.14.1'
    compile 'com.facebook.fresco:animated-webp:0.14.1'
    compile 'com.facebook.fresco:imagepipeline-okhttp3:0.14.1'

 //网络状态
    
    //sd读写权限
    
    

  android:name=".MApp"

封装Activity
/**
 * Description:基类,封装功用功能,方便子类继承,子类只需要实现子类需要的功能即可
 */
public abstract class BaseActivity extends AppCompatActivity{

    private boolean isStatus = false;//沉浸式透明状态栏标示
    private boolean isShowActionBar = true;//是否隐藏actionbar
    private boolean isFullScreen = false;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(bindLayout());
        initView();
        initData();
        setListener();
    }

    protected abstract int bindLayout();//绑定布局

    protected abstract void initView();//初始化控件

    protected abstract void initData();//初始化数据

    protected abstract void setListener();//初始化点击事件


    /**
     * 跳转activity方法
     * @param clazz
     */
    public void startActivity(Class clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }
    /**
     * 跳转activity方法,带参数
     * @param clazz
     */
    public void startActivity(Bundle bundle,Class clazz) {
        Intent intent = new Intent(this, clazz);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void setStatus(boolean status) {
        isStatus = status;
        if (isStatus){
            //判断当前设备的版本号》=19的时候,走这个代码块,这个用于版本适配
            if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){

                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
        }
    }

    public void setShowActionBar(boolean showActionBar) {
        isShowActionBar = showActionBar;

        if (isShowActionBar){
            getSupportActionBar().show();
        }else{
            getSupportActionBar().hide();
        }
    }

    public void setFullScreen(boolean fullScreen) {
        isFullScreen = fullScreen;
        if (isFullScreen){//是全屏的时候
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    public void showToast(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}

//Bean类
//显示购物车数据
public class CartBean {

    private String code;
    private String msg;
    private List data;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List getData() {
        return data;
    }

    public void setData(List data) {
        this.data = data;
    }

    public static class DataBean {
       
        private String sellerName;
        private String sellerid;
        private List 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 getList() {
            return list;
        }

        public void setList(List 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;
            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;
            }
        }
    }
}

//-------------购物车删改的类
public class AddCartBean {
    /**
     * msg : 加购成功
     * code : 0
     */
    private String msg;
    private String code;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}

//utils
//根目录
public class HttpConfig {
    //retrofit根目录
    public static final String _URL="http://120.27.23.105/";
}
//--------------计算价格的类
public class JisuanUtils {
    /**
     * 提供精确的加法运算。
     * @param v1 被加数
     * @param v2 加数
     * @return 两个参数的和
     */
    public static double add(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }
    /**
     * 提供精确的减法运算。
     * @param v1 被减数
     * @param v2 减数
     * @return 两个参数的差
     */
    public static double sub(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }
    /**
     * 提供精确的乘法运算。
     * @param v1 被乘数
     * @param v2 乘数
     * @return 两个参数的积
     */
    public static double mul(double v1,double v2){
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).doubleValue();
    }

}

//-----------------------网络请求类
/**
 * Description:retrofit工具类
 * 构造者模式如何封装:首先有各种builder过程,最后通过build()方法对对象进行创建
 */
public class RetrofitUtils {

    //创建私有属性
    private static RetrofitUtils mInstance;
    //创建ApiService引用
    private static ApiService apiService;

    /**
     * 声明私有构造方法,类似于单利模式,让调用者无法new出对象,只能通过构造者模式创建对象
     */
    private RetrofitUtils() {

    }

    /**
     * 先后调用的过程,只有对象给build成功之后,才能调用apiservice,这也是retrofit的几个先后的步骤
     * @return
     */
    public ApiService getApiService() {
        return apiService;
    }

    public static class Builder {

        private OkHttpClient okHttpClient;

        private List callAdapterFactorys = new ArrayList<>();
        private List convertFactorys = new ArrayList<>();

        public Builder addCallAdapterFactory(CallAdapter.Factory factory) {
            callAdapterFactorys.add(factory);
            return this;//返回this的目的是:可以链式调用
        }

        public Builder addConverterFactory(Converter.Factory factory) {
            convertFactorys.add(factory);
            return this;
        }

        public Builder client(OkHttpClient okHttpClient) {
            this.okHttpClient = okHttpClient;
            return this;
        }

        /**
         * build方法才是真正的业务逻辑操作,才是真正构建对象的过程
         * @return
         */
        public RetrofitUtils build() {


            Retrofit.Builder builder = new Retrofit.Builder();

            if (convertFactorys != null && convertFactorys.size() == 0) {
                //如果集合中没有对象,我们添加默认的gson解析器
                builder.addConverterFactory(GsonConverterFactory.create());
            }

            for (Converter.Factory convertFactory : convertFactorys) {
                builder.addConverterFactory(convertFactory);
            }

            if (callAdapterFactorys != null && callAdapterFactorys.size() == 0) {
                builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());

            }

            for (CallAdapter.Factory callAdapterFactory : callAdapterFactorys) {
                builder.addCallAdapterFactory(callAdapterFactory);
            }

            //第一步创建retrofit对象
            Retrofit retrofit = builder.client(okHttpClient).baseUrl(HttpConfig._URL)
                    .build();
            //第二步,创建apiservice接口类
            apiService = retrofit.create(ApiService.class);
            //第三步,请求逻辑(这个供外部调用者调用)
            mInstance = new RetrofitUtils();//私有构造方法,只有本类可以new出实例
            return mInstance;
        }
    }
}

//ApiService网络请求接口
public interface ApiService {
    @GET("product/getCarts?source=android")
    Observable rxjavaShowCart(@Query("uid") String uid);

    @POST("product/deleteCart")
    @FormUrlEncoded
    Observable rxjavaDeleteCart(@FieldMap Map map);

    @POST("product/updateCarts")
    @FormUrlEncoded
    Observable rxjavaUpdateCarts(@FieldMap Map map);
}

//model层
//--------删除
public class DeleteCartModel {
    public void deleteCart(String uid,String pid,final DeleteCartCallback deleteCartCallback){
        Map map = new HashMap<>();
        map.put("uid", uid);
        map.put("pid", pid);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new HttpLoggingInterceptor()
                        .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(HttpConfig._URL).build();
        ApiService apiService = retrofit.create(ApiService.class);
        apiService.rxjavaDeleteCart(map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(AddCartBean value) {
                        if (value.getCode().equals("0")) {
                            deleteCartCallback.deleteCartSuccess(value);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        deleteCartCallback.failure(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }
    public interface DeleteCartCallback {
        void deleteCartSuccess(AddCartBean bean);//网络请求成功
        void failure(Throwable t);//网络请求失败
    }
}



//presenter层
public class ShowCartPresenter {
    private final IShowCartView view;
    private final ShowCartModel showCartModel;
    private final DeleteCartModel deleteCartModel;
    private final UpdateCartsModel updateCartsModel;

    public ShowCartPresenter(IShowCartView iShowCartView) {
        showCartModel = new ShowCartModel();
        deleteCartModel = new DeleteCartModel();
        updateCartsModel = new UpdateCartsModel();
        this.view=iShowCartView;
    }
    public void showCart(String uid) {
        showCartModel.showCart(uid, new ShowCartModel.ShowCartCallback() {
            @Override
            public void showCartSuccess(CartBean bean) {
                List data = bean.getData();
                view.showCartSuccess(data);
            }

            @Override
            public void failure(Throwable t) {
                view.showCartfailure(t);
            }
        });
    }

    public void deleteCart(String uid,String pid){
        deleteCartModel.deleteCart(uid, pid, new DeleteCartModel.DeleteCartCallback() {
            @Override
            public void deleteCartSuccess(AddCartBean bean) {
                view.deleteCartSuccess(bean.getMsg());
            }

            @Override
            public void failure(Throwable t) {
                view.deleteCartfailure(t);
            }
        });
    }
    public void updateCarts(String uid,String sellerid,String pid,String selected,String num){
        updateCartsModel.updateCarts(uid, sellerid, pid, selected, num, new UpdateCartsModel.UpdateCartsCallback() {
            @Override
            public void updateCartsSuccess(AddCartBean bean) {
                view.updateCartsSuccess(bean.getMsg());
            }

            @Override
            public void failure(Throwable t) {
                view.updateCartsfailure(t);
            }
        });
    }
}


//view层
public interface IShowCartView {
    void showCartSuccess(List data);//网络请求成功
    void showCartfailure(Throwable t);//网络请求失败(断网,服务器崩溃,接口地址不正确,弱网)
    void jisuan(String count,String priceAll);
    void deleteCartSuccess(String str);//网络请求成功
    void deleteCartfailure(Throwable t);//网络请求失败(断网,服务器崩溃,接口地址不正确,弱网)
    void updateCartsSuccess(String str);//网络请求成功
    void updateCartsfailure(Throwable t);//网络请求失败(断网,服务器崩溃,接口地址不正确,弱网)
}

//自定义加减器
public class AddMinusView extends LinearLayout {

    private OnAddMinusClickListener listener;
    private EditText etNumber;

    //对外提供一个点击的回调接口
    public interface OnAddMinusClickListener{
        void onAddClick(View v);
        void onMinusClick(View v);
        void onEtNumberClick(View v);
    }

    public void setOnAddMinusClickListener(OnAddMinusClickListener listener){
        if(listener!=null){
            this.listener=listener;
        }
    }
    public AddMinusView(Context context) {
        this(context,null);
    }

    public AddMinusView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public AddMinusView(Context context, @Nullable 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_minus,this);

        //获取控件
        TextView txtminus=findViewById(R.id.txt_minus);
        TextView txtAdd=findViewById(R.id.txt_add);
        etNumber = findViewById(R.id.et_number);


        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AddMinusViewStyle);

        String leftText = typedArray.getString(R.styleable.AddMinusViewStyle_left_text);
        String rightText = typedArray.getString(R.styleable.AddMinusViewStyle_right_text);
        String middleText = typedArray.getString(R.styleable.AddMinusViewStyle_middle_text);
        int color = typedArray.getColor(R.styleable.AddMinusViewStyle_left_text_color, Color.RED);

        txtminus.setText(leftText);
        txtAdd.setText(rightText);
        etNumber.setText(middleText);
        txtminus.setTextColor(color);

        //回收
        typedArray.recycle();


        txtminus.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onMinusClick(view);
            }
        });

        txtAdd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onAddClick(view);
            }
        });
        etNumber.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onEtNumberClick(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;
    }
}

//---XML

    

    
    



//MainActivity
public class MainActivity extends BaseActivity implements IShowCartView,View.OnClickListener {

    private ExpandableListView expandable;
    private CheckBox checkBox;
    private TextView cart_priceAll;
    private TextView cart_count;
    private List data;
    private CartAdapter cartAdapter;
    private ShowCartPresenter showCartPresenter;
    private TextView cart_editor;
    private boolean flag=true;
    private Button cart_jiesuan;
    private Button cart_delete;

    @Override
    protected int bindLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        showCartPresenter = new ShowCartPresenter(this);
        showCartPresenter.showCart("12400");
        cart_editor = findViewById(R.id.cart_editor);
        expandable = findViewById(R.id.cart_expandable);
        checkBox = findViewById(R.id.cart_checkBox);
        cart_priceAll = findViewById(R.id.cart_priceAll);
        cart_count = findViewById(R.id.cart_count);
        cart_jiesuan = findViewById(R.id.cart_jiesuan);
        cart_delete = findViewById(R.id.cart_delete);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void setListener() {
        checkBox.setOnClickListener(this);
        cart_editor.setOnClickListener(this);
        cart_delete.setOnClickListener(this);
    }

    @Override
    public void showCartSuccess(final List data) {
        this.data=data;
        cartAdapter = new CartAdapter(MainActivity.this,data, this);
        expandable.setAdapter(cartAdapter);
        //展开所有的列表
        int childCount = cartAdapter.getGroupCount();
        for (int i = 0; i < childCount; i++) {
            expandable.expandGroup(i);
        }
    }

    @Override
    public void showCartfailure(Throwable t) {
        Log.d("异常showCart", t.toString());
    }

    @Override
    public void jisuan(String count, String priceAll) {
        cart_count.setText("共"+count+"件商品");
        cart_priceAll.setText("总计:"+priceAll);
    }
    //--------------------------------删除购物车
    @Override
    public void deleteCartSuccess(String str) {
        Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void deleteCartfailure(Throwable t) {
        Log.d("异常deleteCart", t.toString());
    }
    //----------------------------------修改数量
    @Override
    public void updateCartsSuccess(String str) {
        Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void updateCartsfailure(Throwable t) {
        Log.d("异常updateCarts", t.toString());
    }


    //----------------------点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cart_checkBox:
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setCheck(!data.get(i).isCheck());
                    List list = data.get(i).getList();
                    for (int j = 0; j < list.size(); j++) {
                        list.get(j).setCheck(!list.get(j).isCheck());
                    }
                }
                cartAdapter.jS();
                cartAdapter.notifyDataSetChanged();
                break;
            case R.id.cart_editor:
                if (flag){
                    cart_editor.setText("完成");
                    cart_delete.setVisibility(View.VISIBLE);
                    cart_jiesuan.setVisibility(View.INVISIBLE);
                    cart_priceAll.setVisibility(View.INVISIBLE);
                    cart_count.setVisibility(View.INVISIBLE);
                    flag=false;
                }else {
                    cart_editor.setText("编辑");
                    cart_delete.setVisibility(View.INVISIBLE);
                    cart_jiesuan.setVisibility(View.VISIBLE);
                    cart_priceAll.setVisibility(View.VISIBLE);
                    cart_count.setVisibility(View.VISIBLE);
                    flag=true;
                }
                break;
            case R.id.cart_delete:
                List toBeDeleteGroups = new ArrayList();
                //待删除的组元素
                for (int i = 0; i < data.size(); i++) {
                    CartBean.DataBean group = data.get(i);
                    if (data.get(i).isCheck()) {
                        toBeDeleteGroups.add(group);
                    }
                    List toBeDeleteChilds = new ArrayList();//待删除的子元素
                    List list = data.get(i).getList();
                    for (int j = 0; j < list.size(); j++) {
                        if (list.get(j).isCheck()) {
                            toBeDeleteChilds.add(list.get(j));
                                showCartPresenter.deleteCart("12400",list.get(j).getPid()+"");

                        }
                    }
                    list.removeAll(toBeDeleteChilds);
                }
                data.removeAll(toBeDeleteGroups);
                cart_count.setText("共"+0+"件商品");
                cart_priceAll.setText("总计:"+0.0);
                //重新设置购物车
                cartAdapter.notifyDataSetChanged();
                break;
        }
    }
}

//---适配器
public class CartAdapter extends BaseExpandableListAdapter {
    private final IShowCartView IShowCartView;
    private final Context context;
    private final List list;
    private GroupViewHolder holder;
    private ChildViewHolder childholder;


    public CartAdapter(Context context, List data, IShowCartView IShowCartView) {
        this.IShowCartView=IShowCartView;
        this.context=context;
        this.list=data;
    }
    @Override
    public int getGroupCount() {
        return list.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return list.get(groupPosition).getList().size();
    }
    @Override
    public Object getGroup(int groupPosition) {
        return list.get(groupPosition);
    }
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return list.get(groupPosition).getList().get(childPosition);
    }
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }
    @Override
    public boolean hasStableIds() {
        return false;
    }
    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        if(convertView==null){
            holder = new GroupViewHolder();
            convertView = View.inflate(context, R.layout.cart_groupitem, null);
            holder.group_box = convertView.findViewById(R.id.group_box);
            holder.group_name = convertView.findViewById(R.id.group_name);
            convertView.setTag(holder);
        }else{
            holder = (GroupViewHolder) convertView.getTag();
        }
        holder.group_box.setChecked(list.get(groupPosition).isCheck());
        holder.group_name.setText(list.get(groupPosition).getSellerName());
        holder.group_box.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isCleked = list.get(groupPosition).isCheck();
                isCleked=!isCleked;
                list.get(groupPosition).setCheck(isCleked);
                List beans = CartAdapter.this.list.get(groupPosition).getList();
                for (int i = 0; i < beans.size() ; i++) {
                    beans.get(i).setCheck(isCleked);
                }
                jS();
                notifyDataSetChanged();
            }
        });
        return convertView;
    }
    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        if (convertView==null){
            convertView = View.inflate(context, R.layout.cart_childitem, null);
            childholder = new ChildViewHolder();
            childholder.child_box = convertView.findViewById(R.id.child_box);
            childholder.child_img = convertView.findViewById(R.id.child_img);
            childholder.child_subhead = convertView.findViewById(R.id.child_subhead);
            childholder.child_price = convertView.findViewById(R.id.child_price);
            childholder.child_adm = convertView.findViewById(R.id.child_adm);
            convertView.setTag(childholder);
        }else{
            childholder = (ChildViewHolder) convertView.getTag();
        }
        childholder.child_box.setChecked(list.get(groupPosition).getList().get(childPosition).isCheck());
        String images = list.get(groupPosition).getList().get(childPosition).getImages();
        String image = images.split(".jpg")[0] + ".jpg";
        childholder.child_img.setImageURI(Uri.parse(image));
        childholder.child_subhead.setText(list.get(groupPosition).getList().get(childPosition).getSubhead());
        childholder.child_price.setText("售价为:"+list.get(groupPosition).getList().get(childPosition).getPrice());
        childholder.child_adm.setNumber(list.get(groupPosition).getList().get(childPosition).getNum());
        childholder.child_box.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isCleked = list.get(groupPosition).getList().get(childPosition).isCheck();
                isCleked=!isCleked;
                list.get(groupPosition).getList().get(childPosition).setCheck(isCleked);
                List beans = CartAdapter.this.list.get(groupPosition).getList();
                boolean flag=true;
                for (int i = 0; i < beans.size() ; i++) {
                    if (!beans.get(i).isCheck()) {
                        flag=false;
                    }
                }
                list.get(groupPosition).setCheck(flag);
                jS();
                notifyDataSetChanged();
            }
        });
        childholder.child_adm.setOnAddMinusClickListener(new AddMinusView.OnAddMinusClickListener() {
            @Override
            public void onAddClick(View v) {
                int num = list.get(groupPosition).getList().get(childPosition).getNum();
                num++;
                list.get(groupPosition).getList().get(childPosition).setNum(num);
                jS();
                notifyDataSetChanged();
            }
            @Override
            public void onMinusClick(View v) {
                int num = list.get(groupPosition).getList().get(childPosition).getNum();
                num--;
                if(num<=0) {
                    Toast.makeText(context, "最小数量为1", Toast.LENGTH_SHORT).show();
                    return;
                }
                list.get(groupPosition).getList().get(childPosition).setNum(num);
                jS();
                notifyDataSetChanged();
            }

            @Override
            public void onEtNumberClick(View v) {
                final AlertDialog builder = new AlertDialog.Builder(context).create();
                builder.setTitle("温馨提示");
                View inflate = View.inflate(context, R.layout.cart_update, null);
                builder.setView(inflate);
                TextView add = inflate.findViewById(R.id.goods_add);
                TextView minus = inflate.findViewById(R.id.goods_minus);
                final EditText goods_num = inflate.findViewById(R.id.goods_num);
                Button cancel = inflate.findViewById(R.id.goods_cancel);
                Button confirm = inflate.findViewById(R.id.goods_confirm);
                goods_num.setText(list.get(groupPosition).getList().get(childPosition).getNum()+"");
                add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int num = Integer.parseInt(goods_num.getText().toString());
                        num++;
                        goods_num.setText(num+"");
                    }
                });
                minus.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int num = Integer.parseInt(goods_num.getText().toString());
                        num--;
                        if(num<=0) {
                            Toast.makeText(context, "最小数量为1", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        goods_num.setText(num+"");
                    }
                });
                confirm.setOnClickListener(new View.OnClickListener() {
                    private String uid;
                    @Override
                    public void onClick(View v) {
                        CartBean.DataBean.ListBean bean = list.get(groupPosition).getList().get(childPosition);
                        new ShowCartPresenter(IShowCartView).updateCarts("12400",bean.getSellerid()+"",bean.getPid()+"",bean.getSelected()+"",goods_num.getText().toString());
                        list.get(groupPosition).getList().get(childPosition).setNum(Integer.parseInt(goods_num.getText().toString()));
                        notifyDataSetChanged();
                        builder.dismiss();
                    }
                });
                builder.show();
            }
        });

        return convertView;
    }
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }
    class GroupViewHolder{
        public CheckBox group_box;
        public TextView group_name;
    }
    class ChildViewHolder{
        public CheckBox child_box;
        public ImageView child_img;
        public TextView child_subhead;
        public TextView child_price;
        public AddMinusView child_adm;

    }

    /**
     * 计算数量和价格
     * 通过遍历一级的得到二级的CheckBox,如果是选择的选中状态的话,就统计它们的总计的数量和价格
     */
    public void jS(){
        double priceAll = 0;
        int cou=0;
        for (int i = 0; i  beans = this.list.get(i).getList();
            for (int j = 0; j 

//values下
//attrs.xml
 

    

        

        
        

        
    


//---color.XML


    #3F51B5
    #303F9F
    #FF4081
    #FFF8DC
    #8A2BE2
    #FFFFFF
    #C0C0C0
    #FF0000
    #000000


//mapp全局初始化
public class MApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);
    }
}

//drawable下
//edit.XML


    
    

//main的XML


    
        
        
    

    
    
    
    
        
        

        
        

        

//适配器子布局


    
    
    

    

    
    



//适配器父布局


    
    

//适配器弹框


    
        

        
        
    
    
        
//model显示数据
public class ShowCartModel {
    public void showCart(String uid, final ShowCartCallback showCartCallback){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new HttpLoggingInterceptor()
                        .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(HttpConfig._URL).build();
        ApiService apiService = retrofit.create(ApiService.class);
        apiService.rxjavaShowCart(uid).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CartBean value) {
                        if (value.getCode().equals("0")) {
                            showCartCallback.showCartSuccess(value);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showCartCallback.failure(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }
    public interface ShowCartCallback {
        void showCartSuccess(CartBean bean);//网络请求成功

        void failure(Throwable t);//网络请求失败
    }
}

//----------修改
public class UpdateCartsModel {
    public void updateCarts(String uid,String sellerid,String pid,String selected,String num,final UpdateCartsCallback updateCartsCallback){
        Map map = new HashMap<>();
        map.put("uid", uid);
        map.put("sellerid", sellerid);
        map.put("pid", pid);
        map.put("selected", selected);
        map.put("num", num);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new HttpLoggingInterceptor()
                        .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(HttpConfig._URL).build();
        ApiService apiService = retrofit.create(ApiService.class);
        apiService.rxjavaUpdateCarts(map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(AddCartBean value) {
                        if (value.getCode().equals("0")) {
                            updateCartsCallback.updateCartsSuccess(value);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        updateCartsCallback.failure(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }
    public interface UpdateCartsCallback {
        void updateCartsSuccess(AddCartBean bean);//网络请求成功

        void failure(Throwable t);//网络请求失败
    }
}






你可能感兴趣的:(购物车)