Android购物车实现—商城APP03

Android项目实战:商城APPday03-购物车实现

  • day03
    • 内容
      • 1. 购物车存储器类
      • 2. 购物车展示页面
      • 3. 购物车数据的展现
      • 4. 购物车商品选中和商品总价计算
      • 5. 购物车编辑实现
    • 盲区
  • 其他实战
    • 商城
    • 新闻

不否认努力,继续加油!

学习整理重点、盲区,笔记如下:干干巴巴,麻麻赖赖,一点都不圆润……
源码 已上传至集哈:ShoppingMall.
https://github.com/SmileAlfred/ShoppingMall

day03

内容

1. 购物车存储器类

  1. 存储类

    public class CartStorage {
        public static final String JSON_CART = "json_cart";
        private Context context;
        //优化过的HashMap集合
        private SparseArray<GoodsBean> datas;
        private static CartStoragecartProvider;
        private CartProvider(Context context) {
            this.context = context;
            datas = new SparseArray<>(100);
            listToSparse();
        }
        public static CartStorage getInstance() {
            if (CartStorage == null) {
                CartStorage = new CartProvider(MyAppliction.getContext());
            }
            return cartProvider;
        }
        private void listToSparse() {
            List<GoodsBean> carts = getAllData();
            //放到 sparseArry 中
            if (carts != null && carts.size() > 0) {
                for (int i = 0; i < carts.size(); i++) {
                    GoodsBean goodsBean = carts.get(i);
                    datas.put(Integer.parseInt(goodsBean.getProduct_id()),
                            goodsBean);
                }
            }
        }
        private List<GoodsBean> parsesToList() {
            List<GoodsBean> carts = new ArrayList<>();
            if (datas != null && datas.size() > 0) {
                for (int i = 0; i < datas.size(); i++) {
                    GoodsBean shoppingCart = datas.valueAt(i);
                    carts.add(shoppingCart);
                }
            }
            return carts;
        }
        public List<GoodsBean> getAllData() {
            return getDataFromLocal();
        }
        //本地获取json数据,并且通过Gson解析成list列表数据
        public List<GoodsBean> getDataFromLocal() {
            List<GoodsBean> carts = new ArrayList<>();
            //从本地获取缓存数据
            String savaJson = CacheUtils.getString(context, JSON_CART);
            if (!TextUtils.isEmpty(savaJson)) {
                //把数据转换成列表
                carts = new Gson().fromJson(savaJson, new TypeToken<List<GoodsBean>>() {
                }.getType());
            }
            return carts;
        }
        public void addData(GoodsBean cart) {
            GoodsBean tempCart = datas.get(Integer.parseInt(cart.getProduct_id()));
            if (tempCart != null) {
                tempCart.setNumber(tempCart.getNumber() + 1);
            } else {
                tempCart = cart;
                tempCart.setNumber(1);
            }
            datas.put(Integer.parseInt(tempCart.getProduct_id()), tempCart);
            commit();
        }
        public void deleteData(GoodsBean cart) {
            datas.delete(Integer.parseInt(cart.getProduct_id()));
            commit();
        }
        public void updataData(GoodsBean cart) {
            datas.put(Integer.parseInt(cart.getProduct_id()), cart);
            commit();
        }
        //保存数据
        private void commit() {
            //把 parseArray 转换成list
            List<GoodsBean> carts = parsesToList();
            //把转换成String
            String json = new Gson().toJson(carts);
            CacheUtils.putString(context, JSON_CART, json);
        }
    }
    
  2. 添加依赖:implementation 'com.google.code.gson:gson:2.8.6'

  3. 缓存文本工具类

    public class CacheUtils {
        public static String getString(Context context, String key) {
            SharedPreferences sp = context.getSharedPreferences("atguigu",Context.MODE_PRIVATE);
            return sp.getString(key,"");
        }
        public static void saveString(Context context, String key,String value) {
            SharedPreferences sp = context.getSharedPreferences("atguigu",Context.MODE_PRIVATE);
            sp.edit().putString(key,value).commit();
        }
    }
    
  4. 在 GoodsInfoActivity 添加商品

    if (v == btnGoodInfoAddcart) { 
    	//添加购物车 
    	cartProvider.addData(goods_bean); 
    	Toast.makeText(GoodsInfoActivity.this, "添加购物车", Toast.LENGTH_SHORT).show(); 
    }
    

2. 购物车展示页面

  1. 页面分析:

    最外边是 LinearLayout
    	1:相对布局(标题)
    	2:View 分割线
    	3:FrameLayou
    		1:LinearLayout
    			1:RecyclerView
    			2:LinearLayout(结算)
    			3:LinearLayout(删除)
    		2:空车显示布局 empty_cart.xml
    

Android购物车实现—商城APP03_第1张图片Android购物车实现—商城APP03_第2张图片

3. 购物车数据的展现

  1. item 布局
  2. ShoppingCartFragment 初始化布局
  3. 适配器 ShopCartAdapter

4. 购物车商品选中和商品总价计算

  1. 商品总价格计算

    public void showTotalPrice() {
        tvShopcartTotal.setText("合计:" + getTotalPrice());
    }
    // 计算总价格
    public double getTotalPrice() {
        double totalPrice = 0.0;
        if (datas != null && datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                GoodsBean goodsBean = datas.get(i);
                if(goodsBean.isSelected()){
                    totalPrice = totalPrice + Double.valueOf(goodsBean.getNumber()) * Double.valueOf(goodsBean.getCover_price());
                }
            }
        }
        return totalPrice;
    }
    
  2. 增加商品或者减少商品的时候计算总价格

    holder.addSubView.setValue(goodsBean.getNumber());
    holder.addSubView.setOnNumberChangeListener(new AddSubView.OnNumberChangeListener() {
        @Override
        public void onNumberChange(int value) {
            goodsBean.setNumber(value);
            CartStorage.getInstance().updateData(goodsBean);
            //刷新适配器
            notifyItemChanged(position);
            showTotalPrice();
        }
    });
    
  3. 设置点击某一条 item

    public interface  OnItemClickListener{
        // 当点击某条的时候被回调
       public void  onItemClick(int position);
    }
    private OnItemClickListener onItemClickListener;
    // 设置item的监听
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
    
    setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(int position) {
            GoodsBean goodsBean = datas.get(position);
            goodsBean.setSelected(!goodsBean.isSelected());
            notifyItemChanged(position);
            checkAll();
            showTotalPrice();
        }
    });
    
  4. 全选和反选

     public void checkAll() {
         if (datas != null && datas.size() > 0) {
             for (int i = 0; i < datas.size(); i++) {
                 if (datas.get(i).isChildSelected()) {
                     checkboxAll.setChecked(false);
                     cb_all.setChecked(false);
                     return;
                 } else {
                     checkboxAll.setChecked(true);
                     cb_all.setChecked(true);
                 }
             }
         }
     }
    //CheckBox的点击事件
    checkboxAll.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //1.得到状态
            boolean isCheck = checkboxAll.isChecked();
            //2.根据状态设置全选和非全选
            checkAll_none(isCheck);
            //3.计算总价格
            showTotalPrice();
        }
    });
    //设置全选和非全选
    public void checkAll_none(boolean isCheck) {
        if (datas != null && datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                GoodsBean goodsBean = datas.get(i);
                goodsBean.setSelected(isCheck);
                notifyItemChanged(i);
            }
        } else {
            checkboxAll.setChecked(false);
        }
    }
    

5. 购物车编辑实现

  1. 设置点击事件和定义状态;点击编辑按钮,调出删除和收藏按钮;

    //编辑状态、完成状态
    private static final int ACTION_EDIT = 1;
    private static final int ACTION_COMPLETE = 2;
    //设置默认的编辑状态
    tvShopcartEdit.setTag(ACTION_EDIT);
    tvShopcartEdit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int action = (int) v.getTag();
            if (action == ACTION_EDIT) {
                //切换为完成状态
                showDelete();
            } else {
                //切换成编辑状态
                hideDelete();
            }
        }
    });
    
  2. 在适配器中删除选中的 item

    public void deleteData() {
        if (datas != null && datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                GoodsBean goodsBean = datas.get(i);
                if (goodsBean.isSelected()) {
                    datas.remove(goodsBean);
                    CartStorage.getInstance().deleteData(goodsBean);
                    notifyItemRemoved(i);
                    i--;
                }
            }
        }
    }
    

盲区

  1. 声明:本博客根据尚硅谷项目实战: 硅谷商城.学习整理;

其他实战

商城

  1. day01
    第一节学习笔记:链接: 商城APP01—框架搭建.
  2. day02
    第二节学习笔记:链接: 商城APP02—主页实现.

新闻

Android项目实战——新闻APP 学习笔记:链接: 新闻APP.

你可能感兴趣的:(Android学习总结)