购物车简单MVP构建及okhttp

**使用接口:**http://120.27.23.105/product/getCarts?uid=100
导入依赖:

//okHttp依赖
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    //glide加载图片依赖
    implementation 'com.github.bumptech.glide:glide:4.8.0'
    // recyclerview依赖
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.android.support:recyclerview-v7:28.0.0'

使用权限

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

效果图:
在这里插入图片描述
drawable下自定义结算按钮qujiesuan.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <corners android:radius="200dp"/>
    <solid android:color="#e53e42"/>
    <size android:height="60dp" android:width="130dp"/>
</shape>

物品展示页面布局MainActivity

<?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=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Hello World!"
        />
    <LinearLayout
        android:gravity="center_horizontal"
        android:padding="10dp"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <CheckBox
            android:background="@drawable/ic_action_unselected"
            android:button="@null"
            android:id="@+id/quanxuan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:textStyle="bold"
            android:layout_marginLeft="10dp"
            android:textSize="23sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全选"              />
        <LinearLayout
            android:padding="10dp"
            android:layout_marginLeft="10dp"
            android:orientation="vertical"
            android:layout_width="0dp"
            android:layout_weight="1"
            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:id="@+id/total_num"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="共0件商品"
                />
        </LinearLayout>
        <TextView
            android:gravity="center"
            android:textSize="25sp"
            android:text="去结算"
            android:textColor="#fff"
            android:background="@drawable/qujiesuan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


    </LinearLayout>

</LinearLayout>

自定义View绘制物品加减CustomJiaJian
CustomJiaJian自定义view

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(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        View view=View.inflate(context,R.layout.custom_jiajian,this);
        reverse=view.findViewById(R.id.reverse);
        add=view.findViewById(R.id.add);
        countEdit=view.findViewById(R.id.count);

        reverse.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String content  = countEdit.getText().toString().trim();
                Integer count = Integer.valueOf(content);
                if (count>1){
                    mCount=count-1;
                    countEdit.setText(mCount+"");
                    //回调给adapter里面
                    if(customListener!=null){
                        customListener.jiajian(mCount);
                    }

                }
            }
        });
        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+"");
                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);
    }
    //这个方法是供recyadapter设置 数量时候调用的
    public void setEditText(int num) {
        if(countEdit !=null) {
            countEdit.setText(num + "");
        }
    }

}
<?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="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    >
    <Button
        android:background="#fff"
        android:textSize="20sp"
        android:id="@+id/reverse"
        android:text="一"
        android:layout_width="50dp"
        android:layout_height="wrap_content" />
    <EditText
        android:textStyle="bold"
        android:textSize="23sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1"
        android:id="@+id/count"
        />
    <Button
        android:id="@+id/add"
        android:background="#fff"
        android:textSize="25sp"
        android:text="+"
        android:layout_width="50dp"
        android:layout_height="wrap_content" />


</LinearLayout>

代码逻辑分层
在这里插入图片描述
okhttp目录下
ICallBack

public interface ICallBack {
    void success(Object o);
    void failed(Exception e);
}

AbstractUiCallBack接口

public abstract class AbstractUiCallBack<T> implements Callback, okhttp3.Callback {
    public abstract void success(T t);
    public abstract void fail(Exception e);
    private Handler handler = null;
    private Class clazz;
    public AbstractUiCallBack(){
        handler = new Handler(Looper.getMainLooper());
        Type type = getClass().getGenericSuperclass();
        Type[] arr = ((ParameterizedType)type).getActualTypeArguments();
        clazz = (Class) arr[0];    }

        public void onFailure(Call call, IOException e) {
        fail(e);
    }

    public void onResponse(Call call, Response response) throws IOException {
        try {
        String result = response.body().string();
        Gson gson = new Gson();
        final  T t = (T) gson.fromJson(result,clazz);
        handler.post(new Runnable() {
            @Override
            public void run() {
                success(t);
                //成功的回调出去
                }
        });
        }catch (Exception e){
            e.printStackTrace();
            fail(e);//失败的回调
        }
    }

    public void failed(IOException e) {

    }
}

OkHttpUtil工具类

public class OkHttpUtil {
    private static  volatile  OkHttpUtil instance;
    private final OkHttpClient httpClient;
    private Handler handler=new Handler(Looper.getMainLooper());



    public static OkHttpUtil getInstance(){
        if (instance==null){
            synchronized (OkHttpUtil.class){
                instance=new OkHttpUtil();
            }
        }
        return instance;
    }
    public OkHttpUtil() {
        HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient=new OkHttpClient.Builder()
                .connectTimeout(5000,TimeUnit.SECONDS)
                .readTimeout(5000,TimeUnit.SECONDS)
                .writeTimeout(5000,TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .build();
    }

    public String getSynchronous(String url,Class clazz,ICallBack callBack) throws IOException {
        Request request=new Request.Builder()
                .get()
                .url(url)
                .build();
        Call call=httpClient.newCall(request);
        Response response=call.execute();


        return Stream2String(response.body().bytes());
    }

    private String Stream2String(byte[] bytes) {
        return new String(bytes);
    }
    public void getAsynchronization(String url, final Class clazz, final AbstractUiCallBack<CartBean> callBack){
        Request request=new Request.Builder()
                .get()
                .url(url)
                .build();
        Call call=httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.failed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String result=response.body().string();
                    Gson gson=new Gson();
                    final Object o = gson.fromJson(result, clazz);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.success((CartBean) o);
                        }
                    });
                }catch (Exception e){
                    callBack.failed((IOException) e);
                }
            }
        });
    }
    public void postAsynchronization(String url, Map<String,String> params, final Class clazz, final ICallBack callBack){
        FormBody.Builder builder=new FormBody.Builder();
        for (Map.Entry<String,String> entry:params.entrySet()) {
            builder.add(entry.getKey(),entry.getValue());
        }
        RequestBody body=builder.build();
        Request request=new Request.Builder()
                .post(body)
                .url(url)
                .build();
        Call call=httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.failed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String result=response.body().string();
                    Gson gson=new Gson();
                    final Object o = gson.fromJson(result, clazz);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.success(o);
                        }
                    });
                }catch (Exception e){
                    callBack.failed(e);
                }
            }
        });
    }
}

model层
ModelCallBack接口

public interface ModelCallBack {
    void success(CartBean cartBean);
    void failure(Exception e);
}

MyModel实现类

public class MyModel {
    public void getData(final ModelCallBack modelCallBack){
        //访问接口
        String path = "http://120.27.23.105/product/getCarts?uid=100";
        OkHttpUtil.getInstance().getAsynchronization(path, CartBean.class, new AbstractUiCallBack<CartBean>() {
            @Override
            public void success(CartBean cartBean) {
                modelCallBack.success(cartBean);
            }
            @Override
            public void fail(Exception e) {
                modelCallBack.failure(e);
            }
        });
    }
}

P层MyPresenter

public class MyPresenter {
    MyModel myModel = new MyModel();
    ViewCallBack viewCallBack;
    public MyPresenter(ViewCallBack viewCallBack) {
        this.viewCallBack = viewCallBack;
    }
    //调用model 层的请求数据
    public void getData(){
        myModel.getData(new ModelCallBack() {
            @Override
            public void success(CartBean cartBean) {
                if(viewCallBack!=null) {
                    viewCallBack.success(cartBean);
                }
            }
                @Override
                public void failure(Exception e) {
                if(viewCallBack!=null) {
                    viewCallBack.failure(e);
                }
            }
        });
    }
    public void detach(){
        viewCallBack=null;
    }
}

V层接口ViewCallBack

public interface ViewCallBack {
    void success(CartBean cartBean);
    void failure(Exception e);
}

bean类CartBean

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 {


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

        public String getSellerName() {
            return sellerName;
        }

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

        public String getSellerid() {
            return sellerid;
        }

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

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

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

        public static class ListBean {


            private double bargainPrice;
            private String createtime;
            private String detailUrl;
            private String images;
            private int num;
            private int pid;
            private double price;
            private int pscid;
            private int selected;
            private int sellerid;
            private String subhead;
            private String title;
            private int isFirst = 1;//1为显示商铺, 2为隐藏商铺
            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;
            }

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

适配器RecyAdapter

public class RecyAdapter extends RecyclerView.Adapter<RecyAdapter.MyViewHolder > {
    Context context;
    private List<CartBean.DataBean.ListBean> list;

    private Map<String,String> map = new HashMap<>();
    public RecyAdapter(Context context) {
        this.context = context;
    }
    /**
     * *
     * 添加数据并更新显示
     *
     * * */
    public void add(CartBean cartBean){
        //传进来的是bean对象
        if(list == null){
            list = new ArrayList<>();
        }
        //第一层遍历商家和商品

        for (CartBean.DataBean shop : cartBean.getData()){
            //把商品的id和商品的名称添加到map集合里 ,,为了之后方便调用
            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){
            //如果是第一条数据就设置isFirst为1
            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());
                    }
                }
            }
        }
    }


    /*@NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(context, R.layout.recy_cart_item,null);
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;

    }*/
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.recy_cart_item,null);
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;

    }


    public void onBindViewHolder(final MyViewHolder holder, final int i) {

        //final MyViewHolder holder = null;
        /**
         * 设置商铺的 shop_checkbox和商铺的名字 显示或隐藏
         */
        if (list.get(i).getIsFirst()==1){
            //显示商家
            holder.shop_checkbox.setVisibility(View.VISIBLE);
            holder.shop_name.setVisibility(View.VISIBLE);
            //设置shop_checkbox的选中状态
            holder.shop_checkbox.setChecked(list.get(i).isShop_check());
            holder.shop_name.setText(map.get(String.valueOf(list.get(i).getSellerid())));
        }else {
            holder.shop_name.setVisibility(View.GONE);
            holder.shop_checkbox.setVisibility(View.GONE);
        }
        //拆分images字段
        String[] split = list.get(i).getImages().split("\\|");
        //设置商品的图片
        //ImageLoader.getInstance().displayImage(split[0],holder.item_face);
        Glide.with(context).load(split[0]).into(holder.item_face);
        //控制商品的item_checkbox,,根据字段改变
        holder.item_checkbox.setChecked(list.get(i).isItem_check());
        holder.item_name.setText(list.get(i).getTitle());
        holder.item_price.setText(list.get(i).getPrice()+"");
        //调用customjiajian里面的方法设置 加减号中间的数字
        holder.customJiaJian.setEditText(list.get(i).getNum());
        //商铺的shop_checkbox点击事件 ,控制商品的item_checkbox
        holder.shop_checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //先改变数据源中的shop_check
                list.get(i).setShop_check(holder.shop_checkbox.isChecked());
                for (int i=0;i<list.size();i++){
                    //如果是同一家商铺的 都给成相同状态
                    if (list.get(i).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(i).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(i);
                //删除完当前的条目 重新判断商铺的显示隐藏
                setFirst(list);
                //调用重新求和
                sum(list);
                notifyDataSetChanged();
            }
        });
        //加减号的监听,
        holder.customJiaJian.setCustomListener(new CustomJiaJian.CustomListener() {
            @Override
            public void jiajian(int count) {
                //改变数据源中的数量
                list.get(i).setNum(count);
                notifyDataSetChanged();
                sum(list);
            }
            //输入值 求总价
            @Override
            public void shuRuZhi(int count) {
                list.get(i).setNum(count);
                notifyDataSetChanged();
                sum(list);
            }
        });

    }

    /**
     * 计算总价的方法
     * @param list
     */
    private void sum(List<CartBean.DataBean.ListBean> list) {

        //初始的总价为0
        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;
            }
        }
        updateListener.setTotal(totalMoney+"",totalNum+"",allCheck);
    }
    //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);
    }



    @Override
    public int getItemCount() {
        return list==null?0:list.size();
    }
    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 ImageView item_face;
        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_face = (ImageView) itemView.findViewById(R.id.item_face);
        }
    }

    UpdateListener updateListener;
    public void setUpdateListener(UpdateListener updateListener){
        this.updateListener = updateListener;
    }
    //接口
    public interface UpdateListener{
        public void setTotal(String total,String num,boolean allCheck);
    }

}

适配器布局recy_cart_item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="15dp"
    >
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <CheckBox
            android:id="@+id/shop_checkbox"
            android:layout_width="50dp"
            android:layout_height="50dp"
            />
        <TextView
            android:id="@+id/shop_name"
            android:textSize="23sp"
            android:textStyle="bold"
            android:layout_marginLeft="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        >

        <CheckBox
            android:id="@+id/item_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <ImageView
            android:id="@+id/item_face"
            android:src="@mipmap/ic_launcher"
            android:layout_width="100dp"
            android:layout_height="100dp" />
        <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"
                android:maxLines="2"
                />
            <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.peng.shoppingcart.CustomJiaJian
            android:id="@+id/custom_jiajian"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            ></com.example.peng.shoppingcart.CustomJiaJian>

    </LinearLayout>
        <ImageView
            android:id="@+id/item_delete"
            android:layout_marginRight="10dp"
            android:src="@drawable/ic_action_delete"
            android:layout_width="30dp"
            android:layout_height="30dp" />

    </LinearLayout>
</LinearLayout>

MainActivity代码

public class MainActivity extends AppCompatActivity implements ViewCallBack {

    private RecyclerView recyclerView;
    private TextView total_price;
    private TextView total_num;
    private CheckBox quanxuan;
    private MyPresenter myPresenter;
    private RecyAdapter recyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        recyclerView=findViewById(R.id.recycler_view);
        total_price=findViewById(R.id.total_price);
        total_num=findViewById(R.id.total_num);
        quanxuan=findViewById(R.id.quanxuan);
        //1为不选中
        quanxuan.setTag(1);
        LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false);
        recyAdapter=new RecyAdapter(this);
        //myPresenter=new IPresenterImpl(this);
        myPresenter=new MyPresenter(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(recyAdapter);
        myPresenter.getData();
        //myPresenter.requestDataGet(Apis.URL_PRODUCTS_POST,null,CartBean.class);
        //调用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.ic_action_selected);
                }else {
                    quanxuan.setTag(1);
                    quanxuan.setBackgroundResource(R.drawable.ic_action_unselected);
                }
                quanxuan.setChecked(allCheck);
            }
        });
        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.ic_action_selected);
                }else{
                    quanxuan.setTag(1);
                    quanxuan.setBackgroundResource(R.drawable.ic_action_unselected);
                }
                recyAdapter.quanXuan(quanxuan.isChecked());

            }
        });
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        myPresenter.detach();
    }

    @Override
    public void success(CartBean cartBean) {
        recyAdapter.add(cartBean);
    }

    @Override
    public void failure(Exception e) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this,"error",Toast.LENGTH_SHORT).show();
            }
        });

    }
}

猜你喜欢

转载自blog.csdn.net/qq_43580899/article/details/85062156
今日推荐