购物车逻辑 + MVP + 接口回调 +自定义View +拦截器 单例模式+二级列表商品+全选反选+计算总价+加减价格联动

Mainactivity

package com.example.shoppingcart;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.example.shoppingcart.adapter.CartAdapter;
import com.example.shoppingcart.api.ProductApi;
import com.example.shoppingcart.callback.CartUICallBack;
import com.example.shoppingcart.entity.DataBean;
import com.example.shoppingcart.presenter.DataPresenter;
import com.example.shoppingcart.util.OkHttpCallback;
import com.example.shoppingcart.view.DataView;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity implements DataView.ClsView,XRecyclerView.LoadingListener,CartUICallBack {

    private XRecyclerView rv;
    private CheckBox checkbox;
    private DataPresenter dataPresenter;
    private CartAdapter cartAdapter;
    private List carts;
    private int page = 1;
    private HashMap map;

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

    private void initData() {
        //初始化Presenter
        dataPresenter = new DataPresenter(this);
        carts = new ArrayList<>();
        //刷新加载
        shuxinData();

        //设置布局管理器
        rv.setLayoutManager(new LinearLayoutManager(MainActivity.this,OrientationHelper.VERTICAL,false));

        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    for (DataBean.Cart cart : carts) {
                        cart .isChecked = true;
                        for (DataBean.Cart.Product product : cart.list) {
                            product.isProductChecked = true;
                        }
                    }
                }
                else {
                    for (DataBean.Cart cart : carts) {
                        cart .isChecked = false;
                        for (DataBean.Cart.Product product : cart.list) {
                            product.isProductChecked = false;
                        }
                    }
                }
                cartAdapter.notifyDataSetChanged();
                getPrice();
            }
        });
    }

    private void shuxinData() {
        map = new HashMap<>();
        map.put("uid","71");
        map.put("page",page+"");
        dataPresenter.getdatabean(map);
    }

    private void initView() {
        rv = (XRecyclerView) findViewById(R.id.rv);
        checkbox = (CheckBox) findViewById(R.id.checkbox);
        cartAdapter = new CartAdapter(MainActivity.this);
        rv.setAdapter(cartAdapter);


        cartAdapter.setUICallBack(this);
        rv.setLoadingListener(this);

        //允许加载刷新
        rv.setLoadingMoreEnabled(true);
        rv.setPullRefreshEnabled(true);



    }

    private void getPrice() {
        double totaprice = 0;
        for (DataBean.Cart cart : carts) {
            for (DataBean.Cart.Product product : cart.list) {
                if (product.isProductChecked){

                    totaprice += product.price*product.productNum;
                }
            }
        }
        checkbox.setText("¥"+totaprice);
    }

    @Override
    public void success(List list) {
        if (list != null){
            carts=list;
            for (DataBean.Cart cart : carts) {
                for (DataBean.Cart.Product product : cart.list) {
                    product.productNum=1;
                }
            }
            if (page==1){
                cartAdapter.setData(list);
            }else {
                cartAdapter.addData(list);
            }
        }
    }

    @Override
    public void defeated(String msg) {

    }

    @Override
    public void prodeuctsuccess(List list_product) {

    }

    @Override
    public void prodeuctdefeated(String msg) {

    }

    //刷新
    @Override
    public void onRefresh() {
        page = 1;
        shuxinData();
        rv.refreshComplete();
    }

    //加载更多
    @Override
    public void onLoadMore() {
       page++;
        shuxinData();
        rv.loadMoreComplete();
    }

    //接口上面继承生成此方法
    @Override
    public void notifyCart() {
        getPrice();
    }
}

Mainactivity布局




    
        

        

            

            
        

    




Api

package com.example.shoppingcart.api;

public class Api {
    public final static String BASE_URL = "http://www.zhaoapi.cn/";
}

ProductApi

package com.example.shoppingcart.api;

public class ProductApi {
    //购物车
    public final static String CART_URL = Api.BASE_URL+"product/getCarts";
}

DataView

package com.example.shoppingcart.view;

import com.example.shoppingcart.entity.DataBean;
import com.example.shoppingcart.model.DataModel;
import com.example.shoppingcart.util.OkHttpCallback;

import java.util.HashMap;
import java.util.List;

/**
 * 存放接口
 */
public interface DataView {

    public interface ClsView{
        void success(List list);
        void defeated(String msg);
        void prodeuctsuccess(List list_product);
        void prodeuctdefeated(String msg);
    }

    public interface ClsModel{
        void getdatabean(String url,HashMap params,DataModel.ClsModelCallback callback);
    }

    public interface ClsPresenter{

        void getdatabean(HashMap params);
    }




}

OkHttpUtils

package com.example.shoppingcart.util;

import android.os.Handler;

import com.example.shoppingcart.api.ProductApi;
import com.example.shoppingcart.entity.DataBean;
import com.example.shoppingcart.model.DataModel;
import com.example.shoppingcart.view.DataView;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttpUtils{
    private Handler handler = new Handler();
    private static OkHttpUtils instance = new OkHttpUtils();
    private  OkHttpClient okHttpClient;
    public static OkHttpUtils getInstance() {
        if (instance == null){
            synchronized (OkHttpUtils.class){
                instance = new OkHttpUtils();
            }
        }
        return instance;
    }

    private OkHttpUtils(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5,TimeUnit.SECONDS)
                .readTimeout(5,TimeUnit.SECONDS)
                .writeTimeout(5,TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .build();
    }


    public void doGet(String url, HashMap params, final OkHttpCallback okHttpCallback) {



        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (okHttpCallback != null){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            okHttpCallback.defeated("网络异常啦");
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (okHttpCallback != null){
                    if (200 == response.code()){
                        final String result = response.body().string();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                okHttpCallback.success(result);
                            }
                        });
                    }
                }



            }
        });

    }

    public void doPost(String url, HashMap params, final OkHttpCallback okHttpCallback) {

        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry map : params.entrySet()){
            builder.add(map.getKey(),map.getValue());
        }

        FormBody formbody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formbody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (okHttpCallback != null){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            okHttpCallback.defeated("网络异常啦");
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (okHttpCallback != null){
                    if (200 == response.code()){
                        final String result = response.body().string();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                okHttpCallback.success(result);
                            }
                        });
                    }
                }
            }
        });

    }
}

OkHttpCallback

package com.example.shoppingcart.util;

public interface OkHttpCallback {

    void success(String result);
    void defeated(String msg);
}

DataModel

package com.example.shoppingcart.model;

import com.example.shoppingcart.api.ProductApi;
import com.example.shoppingcart.util.OkHttpUtils;
import com.example.shoppingcart.view.DataView;
import com.example.shoppingcart.util.OkHttpCallback;

import java.util.HashMap;

/**
 * 购物车Model层
 */
public class DataModel implements DataView.ClsModel {
    @Override
    public void getdatabean(String url,HashMap params,final ClsModelCallback callback) {

        OkHttpUtils.getInstance().doPost(ProductApi.CART_URL,params, new OkHttpCallback() {
            @Override
            public void success(String result) {
                if (callback != null){
                    callback.datasuccess(result);
                }
            }

            @Override
            public void defeated(String msg) {
                if (callback != null){
                    callback.datadefeated();
                }
            }
        });


    }

    public interface ClsModelCallback{
        void datasuccess(String result);
        void datadefeated();
    }

}

DataPresenter

package com.example.shoppingcart.presenter;

import com.example.shoppingcart.api.ProductApi;
import com.example.shoppingcart.entity.DataBean;
import com.example.shoppingcart.util.OkHttpUtils;
import com.example.shoppingcart.view.DataView;
import com.example.shoppingcart.model.DataModel;
import com.example.shoppingcart.util.OkHttpCallback;
import com.google.gson.Gson;

import java.util.HashMap;

public class DataPresenter implements DataView.ClsPresenter {
        private DataModel dataModel;
        private DataView.ClsView dataView;
        public DataPresenter(DataView.ClsView view){
            this.dataModel = new DataModel();
            this.dataView = view;
        }


    public void getdatabean(HashMap params) {
        dataModel.getdatabean(ProductApi.CART_URL,params, new DataModel.ClsModelCallback() {
            @Override
            public void datasuccess(String result) {
                DataBean dataBean = new Gson().fromJson(result, DataBean.class);
                dataView.success(dataBean.data);
            }

            @Override
            public void datadefeated() {
                dataView.defeated("msg");
            }
        });
    }


}

AddMinusView(自定义View加减器)

package com.example.shoppingcart.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.shoppingcart.R;

public class AddMinusView extends LinearLayout {

    private TextView jian ,jia;
    private EditText et_num;
    private int num = 1;

    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);
        init(context);
    }

    private void init(final Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.addjian_item,this,true);
        jia = findViewById(R.id.jia);
        jian = findViewById(R.id.jian);
        et_num = findViewById(R.id.et_num);
        et_num.setText("1");

        jian.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //num是int类型   转换成String类型
                num = Integer.parseInt(et_num.getText().toString());
                num--;
                if (num == 0){
                    num = 1;
                    Toast.makeText(context,"不能再减了",Toast.LENGTH_SHORT).show();
                    return;
                }
                et_num.setText(num+"");


                if (addMinusViewCallback != null){
                    addMinusViewCallback.numCallback(num);
                }
                addMinusViewCallback.numCallback(num);
            }
        });

        jia.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                num = Integer.parseInt(et_num.getText().toString());
                num++;
                et_num.setText(num+"");
                if (addMinusViewCallback != null){
                    addMinusViewCallback.numCallback(num);
                }
                addMinusViewCallback.numCallback(num);

            }
        });
    }

    private AddMinusCallback addMinusViewCallback;
    public void setAddMinusViewCallback(AddMinusCallback addMinusViewCallback){
            this.addMinusViewCallback = addMinusViewCallback;
    }
    public interface AddMinusCallback{
        void numCallback(int num);
    }

}

addjian_item(自定义加减器布局)



    

        

        
        
    

CartAdapter(一级列表适配器)

package com.example.shoppingcart.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.example.shoppingcart.MainActivity;
import com.example.shoppingcart.R;
import com.example.shoppingcart.callback.CartCallBack;
import com.example.shoppingcart.callback.CartUICallBack;
import com.example.shoppingcart.entity.DataBean;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

public class CartAdapter extends RecyclerView.Adapter implements CartCallBack {
    private CartUICallBack cartUICallBack;
    private Context context;
    private List list;
    private ProductAdapter productAdapter;

    public void setUICallBack(CartUICallBack cartUICallBack) {
        this.cartUICallBack = cartUICallBack;
    }

    public CartAdapter(Context context) {
        this.context = context;
        this.list = new ArrayList<>();
    }
    //设置数据
    public void setData(List list) {
        this.list.clear();
        if (list != null){
            this.list.addAll(list);
        }
        notifyDataSetChanged();
    }
    //加载数据时调用
    public void addData(List list) {
        if (list != null){
            this.list.addAll(list);
        }
        notifyDataSetChanged();
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(this.context, R.layout.shangjia_item, null);
        MyViewHolder viewHolder = new MyViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder viewHolder, final int i){
        viewHolder.ckbox.setChecked(list.get(i).isChecked);
        viewHolder.tv_sj_name.setText(this.list.get(i).sellerName);

        //创建商家商品是适配器
        productAdapter = new ProductAdapter(context,list.get(i).list);
        productAdapter.setCartCallBack(this);
        //给商品设置布局管理器
        viewHolder.xrecyclerview.setLayoutManager(new LinearLayoutManager(context));
        viewHolder.xrecyclerview.setAdapter(productAdapter);

        //一级商家复选框选中状态
        viewHolder.ckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.get(i).isChecked = viewHolder.ckbox.isChecked();
                for (DataBean.Cart.Product product : list.get(i).list) {
                    //点击父复选框   子复选框全部选中
                    product.isProductChecked = list.get(i).isChecked;
                }
                notifyDataSetChanged();
                if (cartUICallBack != null){
                    cartUICallBack.notifyCart();
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return this.list.size();
    }

    @Override
    public void notifyCartItem(boolean isChecked, int postion) {
        //设置以及复选框选中
        list.get(postion+1).isChecked = isChecked;
        notifyDataSetChanged();
    }

    @Override
    public void notifyNum() {
        //数据改变后通知价格联动改变
        if (cartUICallBack != null){
            cartUICallBack.notifyCart();
        }

    }


    public class MyViewHolder extends RecyclerView.ViewHolder {
        private CheckBox ckbox;
        private XRecyclerView xrecyclerview;
        private TextView tv_sj_name;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_sj_name = itemView.findViewById(R.id.tv_sj_name);
            xrecyclerview = itemView.findViewById(R.id.xrecyclerview);
            ckbox = itemView.findViewById(R.id.ckbox);
        }
    }
}

shangjia_item(商家一级列表布局)




    

        

            

            

        

        
    


CartCallBack(一级列表接口回调)

package com.example.shoppingcart.callback;

public interface CartCallBack {

    void notifyCartItem(boolean isChecked ,int postion);
    void notifyNum();

}

ProductAdapter(二级列表适配器)

package com.example.shoppingcart.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.shoppingcart.R;
import com.example.shoppingcart.callback.CartCallBack;
import com.example.shoppingcart.entity.DataBean;
import com.example.shoppingcart.widget.AddMinusView;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.List;

public class ProductAdapter extends XRecyclerView.Adapter {

    private Context context;
    private CartCallBack cartCallBack;


    public void setCartCallBack(CartCallBack cartCallBack) {
        this.cartCallBack = cartCallBack;
    }

    private List list_product;
    public ProductAdapter(Context context, List list_product) {
        this.context = context;
        this.list_product = list_product;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(context, R.layout.product_item, null);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) {
        String[] image = list_product.get(i).images.split("\\|");
        if (image != null && image.length>0){
            Glide.with(context).load(image[0]).into(viewHolder.p_img);
        }
        viewHolder.p_tv_price.setText("¥"+list_product.get(i).price);
        viewHolder.p_tv_title.setText(list_product.get(i).title);
        viewHolder.p_checkb.setChecked(list_product.get(i).isProductChecked);

        viewHolder.p_checkb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击子复选框  父复选框被选中
                list_product.get(i).isProductChecked = viewHolder.p_checkb.isChecked();
                cartCallBack.notifyNum();
                for (DataBean.Cart.Product pu : list_product) {

                    if (!pu.isProductChecked){
                        if (cartCallBack != null){
                            cartCallBack.notifyCartItem(false,list_product.get(i).pos);
                        }
                        return;
                    }
                    cartCallBack.notifyCartItem(true,list_product.get(i).pos);
                }
            }
        });
                viewHolder.addminusView.setAddMinusViewCallback(new AddMinusView.AddMinusCallback() {
                    @Override
                    public void numCallback(int num) {
                        list_product.get(i).productNum = num;
                        cartCallBack.notifyNum();
                    }
                });

    }

    @Override
    public int getItemCount() {
        return list_product.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private CheckBox p_checkb;
        private ImageView p_img;
        private TextView p_tv_title,p_tv_price;
        private AddMinusView addminusView;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            p_checkb = itemView.findViewById(R.id.p_checkb);
            p_img = itemView.findViewById(R.id.p_img);
            p_tv_title = itemView.findViewById(R.id.p_tv_title);
            p_tv_price = itemView.findViewById(R.id.p_tv_price);
            addminusView = itemView.findViewById(R.id.addminusView);
        }
    }
}

product_item(商家二级列表布局)




    

        

            
            
            

                
                

            

        

        

    



CartUICallBack(二级列表接口回调)

package com.example.shoppingcart.callback;

public interface CartUICallBack {
    void notifyCart();
}

DataBean

package com.example.shoppingcart.entity;

import java.util.List;

public class DataBean {

    public String code;
    public String msg;
    public List data;

    public class Cart {
        //一级列表是否选中标志位
        public boolean isChecked;

        public String sellerName;
        public String sellerid;
        public List list;

        public class Product {
            public boolean isProductChecked;//二级
            public String title;
            public String images;
            public double price;
            public String pid;
            //下标
            public int pos;

            //商品数量
            public int productNum =1;
        }


    }
}

你可能感兴趣的:(购物车逻辑 + MVP + 接口回调 +自定义View +拦截器 单例模式+二级列表商品+全选反选+计算总价+加减价格联动)