1. 程式人生 > >購物車的第二種方法的介面卡以及HttpUtils網路工具類

購物車的第二種方法的介面卡以及HttpUtils網路工具類

 

 

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.CompoundButton;
import android.widget.TextView;

import com.bwie.cart1023.R;
import com.bwie.cart1023.bean.Product;
import com.bwie.cart1023.bean.Shopper;

import java.util.List;

 

//ShopperAdapter



public class ShopperAdapter extends RecyclerView.Adapter<ShopperAdapter.ViewHolder> {
    private Context context;
    private List<Shopper<List<Product>>> list;

    public ShopperAdapter(Context context, List<Shopper<List<Product>>> list) {
        this.context = context;
        this.list = list;
    }

    // 一級列表(商家)發生變化的介面
    public interface OnShopperClickListener {
        void onShopperClick(int position, boolean isCheck);
    }

    private OnShopperClickListener shopperClickListener;

    public void setOnShopperClickListener(OnShopperClickListener listener) {
        this.shopperClickListener = listener;
    }


    // 二級列表的加減器監聽
    private ProductAdapter.OnAddDecreaseProductListener productListener;

    public void setOnAddDecreaseProductListener(ProductAdapter.OnAddDecreaseProductListener listener) {
        this.productListener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = View.inflate(context, R.layout.item_shopper, null);
        ViewHolder holder = new ViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        final Shopper<List<Product>> shopper = list.get(position);
        holder.txtShopperName.setText(shopper.getSellerName());

        // 產品的列表
        RecyclerView.LayoutManager pLayoutManager = new LinearLayoutManager(context);
        holder.rvProduct.setLayoutManager(pLayoutManager);
        final ProductAdapter adapter = new ProductAdapter(context, shopper.getList());
        // 給二級列表新增一個加減器的監聽
        if (productListener != null) {
            adapter.setOnAddDecreaseProductListener(productListener);
        }
        // 二級條目(商品)複選框點選事件
        adapter.setOnProductClickListener(new ProductAdapter.OnProductClickListener() {
            @Override
            public void onProductClick(int position, boolean isChecked) {
                // 當前商品未選中,商家也就未選中
                if (!isChecked) {
                    shopper.setChecked(false);
                    // 只要是當前條目未選中,全選複選框也就沒選中
                    shopperClickListener.onShopperClick(position, false);
                } else {
                    // 當前商品如果選中,需要遍歷商家所有的商品是否選中
                    // 迴圈遍歷之前先設定一個true標誌位,只要有一條商品沒有被選中,商家也就選中,標誌位變成false
                    boolean isAllProductSelected = true;
                    for (Product product : shopper.getList()) {
                        if (!product.isChecked()) {
                            isAllProductSelected = false;
                            break;
                        }
                    }
                    shopper.setChecked(isAllProductSelected);
                    // 當前商品選中時,需要迴圈遍歷所有的商家是否被選中來確認外部全選複選框的狀態
                    shopperClickListener.onShopperClick(position, true);
                }
                // 資料發生變化之後重新整理介面卡
                notifyDataSetChanged();
                productListener.onChange(0, 0);
            }
        });

        holder.rvProduct.setAdapter(adapter);

        // 先取消掉之前的點選變化監聽
        holder.cbSHopper.setOnCheckedChangeListener(null);

        // 設定好初始化的狀態
        holder.cbSHopper.setChecked(shopper.isChecked());

        // 等設定完初始化狀態之後再設定我們自己的監聽
        // 商家列表中的複選框
        holder.cbSHopper.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                shopper.setChecked(isChecked);

                // 1.商家被選中的時候,子類所有的商品應該被選中
//                if (isChecked) {
                List<Product> productList = shopper.getList();
                for (Product product : productList) {
                    product.setChecked(isChecked);
                }
                // 子類商品的介面卡重新整理
                adapter.notifyDataSetChanged();
//                }
                // 當點選一級條目的時候,外部的全選按鈕狀態發生變化
                if (shopperClickListener != null) {
                    shopperClickListener.onShopperClick(position, isChecked);
                }
            }
        });
    }

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

    class ViewHolder extends RecyclerView.ViewHolder {
        private CheckBox cbSHopper;
        private TextView txtShopperName;
        private RecyclerView rvProduct;

        public ViewHolder(View itemView) {
            super(itemView);
            cbSHopper = itemView.findViewById(R.id.cb_shopper);
            txtShopperName = itemView.findViewById(R.id.txt_shopper_name);
            rvProduct = itemView.findViewById(R.id.rv_product);
        }
    }
}

 

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

import com.bumptech.glide.Glide;
import com.bwie.cart1023.R;
import com.bwie.cart1023.bean.Product;
import com.bwie.cart1023.utils.StringUtils;
import com.bwie.cart1023.widget.AddDecreaseView;

import java.util.List;

//ProductAdapter 

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
    private Context context;
    private List<Product> list;

    // 二級條目(商品)點選監聽
    public interface OnProductClickListener {
        void onProductClick(int position, boolean isChecked);
    }

    private OnProductClickListener productClickListener;

    public void setOnProductClickListener(OnProductClickListener listener) {
        this.productClickListener = listener;
    }

    // 加減器發生變化的監聽
    public interface OnAddDecreaseProductListener {
        void onChange(int position, int num);
    }

    private OnAddDecreaseProductListener productListener;

    public void setOnAddDecreaseProductListener(OnAddDecreaseProductListener listener) {
        this.productListener = listener;
    }

    public ProductAdapter(Context context, List<Product> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = View.inflate(context, R.layout.item_product, null);
        ViewHolder holder = new ViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final Product product = list.get(position);
        String images = product.getImages();
        // 商品圖片
        if (!TextUtils.isEmpty(images)) {
            String[] strings = images.split("\\|");
            if (strings.length > 0) {
                Glide.with(context)
                        .load(StringUtils.https2Http(strings[0]))
                        .into(holder.imgProduct);
            }
        }

        holder.txtProductName.setText(product.getTitle());
        holder.txtSinglePriice.setText(String.valueOf(product.getPrice()));

        holder.advProduct.setNum(product.getNum());
        // 加減器新增點選事件
        holder.advProduct.setOnAddDecreaseClickListener(new AddDecreaseView.OnAddDecreaseClickListener() {
            @Override
            public void add(int num) {
                product.setNum(num);

                if (productListener != null) {
                    productListener.onChange(position, num);
                }
            }

            @Override
            public void decrease(int num) {
                product.setNum(num);
                if (productListener != null) {
                    productListener.onChange(position, num);
                }
            }
        });


        // 商品的複選框
        holder.cbProduct.setOnCheckedChangeListener(null);
        holder.cbProduct.setChecked(product.isChecked());
        holder.cbProduct.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                product.setChecked(isChecked);
                if (productClickListener != null) {
                    productClickListener.onProductClick(position, isChecked);
                }
            }
        });

    }

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

    class ViewHolder extends RecyclerView.ViewHolder {
        private CheckBox cbProduct;
        private ImageView imgProduct;
        private TextView txtProductName;
        private TextView txtSinglePriice;
        private AddDecreaseView advProduct;

        public ViewHolder(View itemView) {
            super(itemView);
            cbProduct = itemView.findViewById(R.id.cb_product);
            imgProduct = itemView.findViewById(R.id.img_product);
            txtSinglePriice = itemView.findViewById(R.id.txt_single_price);
            advProduct = itemView.findViewById(R.id.adv_product);
            txtProductName = itemView.findViewById(R.id.txt_product_name);
        }
    }
}

 

//以及分好的bean包

//MessageBean

public class MessageBean<T> {
    private String msg;
    private String code;
    private T 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 T getData() {
        return data;
    }

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

//Product

public class Product {

    /**
     * bargainPrice : 22.9
     * createtime : 2017-10-14T21:48:08
     * detailUrl : https://item.m.jd.com/product/2542855.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends
     * images : https://m.360buyimg.com/n0/jfs/t1930/284/2865629620/390243/e3ade9c4/56f0a08fNbd3a1235.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2137/336/2802996626/155915/e5e90d7a/56f0a09cN33e01bd0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t1882/31/2772215910/389956/c8dbf370/56f0a0a2Na0c86ea6.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2620/166/2703833710/312660/531aa913/57709035N33857877.jpg!q70.jpg
     * num : 1
     * pid : 24
     * price : 288
     * pscid : 2
     * selected : 0
     * sellerid : 1
     * subhead : 三隻松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》
     * title : 三隻松鼠 堅果炒貨 零食奶油味 碧根果225g/袋
     */

    private float bargainPrice;
    private String createtime;
    private String detailUrl;
    private String images;
    private int num;
    private int pid;
    private float price;
    private int pscid;
    private int selected;
    private int sellerid;
    private String subhead;
    private String title;
    private boolean isChecked;

    public float getBargainPrice() {
        return bargainPrice;
    }

    public void setBargainPrice(float 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 float getPrice() {
        return price;
    }

    public void setPrice(float 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 boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean checked) {
        isChecked = checked;
    }
}

//Shopper

public class Shopper<T> {
    private String sellerid;
    private String sellerName;
    private boolean isChecked;
    private T list;

    public String getSellerid() {
        return sellerid;
    }

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

    public String getSellerName() {
        return sellerName;
    }

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

    public boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean checked) {
        isChecked = checked;
    }

    public T getList() {
        return list;
    }

    public void setList(T list) {
        this.list = list;
    }
}

//INetCallBack


public interface INetCallBack {
    void success(Object obj);

    void failed(Exception e);
}

//HttpUtils

 private static volatile HttpUtils instance;

    private OkHttpClient client;

    private Handler handler = new Handler(Looper.getMainLooper());

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

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

    public static HttpUtils getInstance() {
        if (instance == null) {
            synchronized (HttpUtils.class) {
                if (null == instance) {
                    instance = new HttpUtils();
                }
            }
        }
        return instance;
    }

    public void get(String url, final INetCallBack callBack, final Type type) {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.failed(e);
                    }
                });
            }

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

//StringUtils

//這個utils是用來更換地址裡面有可能會出現的https的,有的證書過期需要替換

 public static String https2Http(String url) {
        return url.replace("https", "http");
    }

//AddDecreaseView

public class AddDecreaseView extends RelativeLayout implements View.OnClickListener {
    private TextView txtAdd;
    private TextView txtDecrease;
    private TextView txtNum;

    private int num;

    public interface OnAddDecreaseClickListener {
        void add(int num);

        void decrease(int num);
    }


    private OnAddDecreaseClickListener listener;

    public void setOnAddDecreaseClickListener(OnAddDecreaseClickListener listener) {
        this.listener = listener;
    }

    public AddDecreaseView(Context context) {
        this(context, null);
    }

    public AddDecreaseView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AddDecreaseView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        View.inflate(context, R.layout.item_add_decrease, this);
        txtAdd = findViewById(R.id.txt_add);
        txtDecrease = findViewById(R.id.txt_decrease);
        txtNum = findViewById(R.id.txt_num);

        txtNum.setText("1");

        txtAdd.setOnClickListener(this);
        txtDecrease.setOnClickListener(this);

    }

    public void setNum(int num) {
        this.num = num;
        txtNum.setText(num + "");
    }

    public int getNum() {
        return num;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.txt_add:
                num++;
                txtNum.setText(num + "");
                if (listener != null) {
                    listener.add(num);
                }
                break;
            case R.id.txt_decrease:
                if (num > 1) {
                    num--;
                }
                txtNum.setText(num + "");
                if (listener != null) {
                    listener.decrease(num);
                }
                break;
        }
    }
}