购物车二级列表的完美实现

这是在Fragment中实现,自己使用的地方根据自己需求来定义
public class Fragment_GouWuChe extends Fragment {

    private View view;
    private GWC_dao dao;
    private ExpandableListView EX_listview;
    private TextView notdata;
    private CheckBox checkAll;
    private TextView price;
    private TextView checked_shop;
    private FM_GWC_Adapter adapter;
    private TextView total_price;
    private static ArrayList<SQliteBean> list;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = View.inflate(getContext(), R.layout.fragment_gouwuche, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        //当这个集合等于空的时候来查询数据
        list = dao.selectAll();
        //如果数据库无内容,显示TextView的提示无内容,recyclerView影藏
        if (list.size() > 0) {
            //如果出具库有数据就处理相关逻辑
            Listener(list);
        } else {
            //数据库没有东西的时候让TextView显示购物车为空
            notdata.setVisibility(View.VISIBLE);
        }
        //点击一级列表删除信息
        EX_listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //查询下标对应的商品id,在添加数据库的时候会专门来保存商品id
                String gc_id = list.get(position).getGc_id();
                //执行删除数据库
                dao.deleteData(gc_id);
                Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                //删除成功以后.重新查询数据库
                list = dao.selectAll();
                //如果数据无内容,提示无内容,recyclerVIew影藏
                if (list.size() > 0) {
                    //如果出具库有数据就处理相关逻辑
                    Listener(list);
                } else {
                    //数据库没有东西的时候让TextView显示购物车为空
                    notdata.setVisibility(View.VISIBLE);
                }
                return true;
            }
        });
    }

    //执行相关事件
    private void Listener(ArrayList<SQliteBean> list) {
        //有数据以后把这个textview隐藏
        notdata.setVisibility(View.GONE);
        //为二级列表设置适配器,list就是从数据库查询出来的数据
        adapter = new FM_GWC_Adapter(list, getContext());
        EX_listview.setAdapter(adapter);

        //全选按钮
        checkAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //代用适配器中的自定义方法,循环遍历二级列表,设置全选或全不选
                adapter.setCheckedAll();
                //得到查询到的选中项目的总条目数,和总价格
                String[] split = adapter.getShopNumber().split(",");
                //设置选中的商品个数
                checked_shop.setText("(" + split[1] + ")");
                //设置价格
                total_price.setText("合计:¥" + split[0]);
            }
        });
        //刷新选中的个数,和判断是否全部选中
        adapter.getNumberAndIsCheckAll(new FM_GWC_Adapter.NumberAndIsCheckAll() {
            @Override
            public void getNumber(View view, String shop, boolean ischecked) {
                //split[0]=价格, split[1]个数
                String[] split = shop.split(",");
                //设置选中的商品个数
                checked_shop.setText("(" + split[1] + ")");
                //设置价格
                total_price.setText("合计:¥" + split[0]);
                //设置商品全部选中的时候,全选按钮也自动选中
                checkAll.setChecked(ischecked);
            }
        });

        //设置当所有商品全部选中的时候,全选按钮也设置选中状态
        checkAll.setChecked(adapter.selectShopAll());
        //刷新适配器
        adapter.notifyDataSetChanged();
    }

    private void initView() {
        //显示数据
        EX_listview = (ExpandableListView) view.findViewById(R.id.gwc_ex_listview);
        //如果购物车空的时候让他显示购物车为空
        notdata = (TextView) view.findViewById(R.id.notdata);
        //操作数据库
        dao = new GWC_dao(getContext());
        //全选按钮
        checkAll = (CheckBox) view.findViewById(R.id.checkAll);
        //价格
        price = (TextView) view.findViewById(R.id.price);
        //结算的时候选中的店铺个数
        checked_shop = (TextView) view.findViewById(R.id.checked_shop);
        //总价格
        total_price = (TextView) view.findViewById(R.id.price);
        //定位按钮重启Activity,刷新数据
        view.findViewById(R.id.dingwei).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().recreate();
                getActivity().overridePendingTransition(R.anim.shape02, R.anim.shape01);
            }
        });
    }
}
 
//下面是二级列表 ExpandableListView 的适配器的逻辑,实际的数据根据自己需求来改变
//可以直接复制来使用
public class FM_GWC_Adapter extends BaseExpandableListAdapter {
    private ArrayList<SQliteBean> list;//数据库的信息
    private Context context;
    private ArrayList<HashMap<Integer, Boolean>> groupList;//保存一级列表checkbox状态
    private ArrayList<ArrayList<HashMap<Integer, Boolean>>> childList;//保存二级列表checkbox状态
    private String[] groups;//保存一级列表内容
    private DataActivity_Bean.DatasBean.GoodsCommendListBean[][] childs;//保存二级列表内容
    //保存商品单价和数量,里面的GWC_Data是自定义的JavaBean,根据自己需求来定义属性
    private List<List<GWC_Data>> dataList;

    public FM_GWC_Adapter(ArrayList<SQliteBean> datalist, Context context) {
        this.list = datalist;//传过来的数据库的内容
        this.context = context;
        //初始化数据
        initData();
    }

    //初始化数据
    private void initData() {
        dataList = new ArrayList<>();//保存商品单价和数量
        groupList = new ArrayList<>();//保存一级列表checkbox状态
        childList = new ArrayList<>();//保存二级列表checkbox状态
        groups = new String[list.size()];//保存一级列表内容
        childs = new DataActivity_Bean.DatasBean.GoodsCommendListBean[list.size()][];//保存二级列表内容

        for (int i = 0; i < list.size(); i++) {
            //得到每一个存储商品信息的json数据
            String path = list.get(i).getPath();
            //解析json
            DataActivity_Bean bean = new Gson().fromJson(path, DataActivity_Bean.class);
            //一级列表得到的标题太长,截取几位显示
            String goods_name = bean.getDatas().getGoods_info().getGoods_name().substring(0, 9);
            //保存一级列表的名字,商家1,商家2...
            groups[i] = goods_name + (i + 1);
            //保存一级列表中的checkbox是否选中
            HashMap<Integer, Boolean> gmap = new HashMap<>();
            gmap.put(i, false);
            groupList.add(gmap);

            //这个是设置二级列表的数据
            List<DataActivity_Bean.DatasBean.GoodsCommendListBean> goods_list = bean.getDatas().
                    getGoods_commend_list();//得到数据里面保存的商品信息的集合
            //这里-5的原因是因为返回的集合太长,只为了实现效果,所以让他只显示了3条数据,方便操作
            DataActivity_Bean.DatasBean.GoodsCommendListBean[] strings =
                    new DataActivity_Bean.DatasBean.GoodsCommendListBean[goods_list.size() - 5];
            ArrayList<HashMap<Integer, Boolean>> listHashMap = new ArrayList<>();
            ArrayList<GWC_Data> gwc_datas = new ArrayList<>();//每个二级列表的单价和数量
            for (int y = 0; y < strings.length; y++) {
                //创建每一个二级列表中数据的HashMap集合,保存状态
                HashMap<Integer, Boolean> hashMap = new HashMap<>();
                hashMap.put(y, false);
                listHashMap.add(hashMap);
                //保存二级列表的数据
                strings[y] = goods_list.get(y);
                //保存单价,默认数量是一个
                gwc_datas.add(new GWC_Data(goods_list.get(y).getGoods_promotion_price(), "1"));
            }
            childList.add(listHashMap);
            childs[i] = strings;
            dataList.add(gwc_datas);
        }

    }

    @Override
    public int getGroupCount() {
        return groups.length;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return childs[groupPosition].length;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return groups[groupPosition];
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return childs[childPosition];
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }


    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        GroupViewHolder groupholder = null;
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.gouwuche_group_item, null);
            groupholder = new GroupViewHolder();
            groupholder.ck = (CheckBox) convertView.findViewById(R.id.group_checkbox);
            groupholder.title = (TextView) convertView.findViewById(R.id.group_name);
            convertView.setTag(groupholder);
        } else {
            groupholder = (GroupViewHolder) convertView.getTag();
        }
        groupholder.title.setText(groups[groupPosition]);

        final GroupViewHolder finalGroupholder = groupholder;
        groupholder.ck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<Integer, Boolean> hashMap = groupList.get(groupPosition);
                hashMap.put(groupPosition, !groupList.get(groupPosition).get(groupPosition));
                //点击一级列表,让二级列表全部选中
                setChildCheckBox(groupPosition);
                //得到选中的商品数和价格拼成的字符串
                String shop = getShopNumber();
                //查询是否全部选中
                boolean b = selectShopAll();
                //调用自定义接口,把数据传出去
                numberAndIsCheckAll.getNumber(v, shop, b);
                notifyDataSetChanged();
            }
        });

        Boolean aBoolean = groupList.get(groupPosition).get(groupPosition);
        groupholder.ck.setChecked(aBoolean);
        return convertView;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildViewHolder holder = null;
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.gouwuche_child_item, null);
            holder = new ChildViewHolder();
            holder.ck = (CheckBox) convertView.findViewById(R.id.child_checkbox);
            holder.img = (ImageView) convertView.findViewById(R.id.gwc_item_img);
            holder.title = (TextView) convertView.findViewById(R.id.gwc_item_name);
            holder.price = (TextView) convertView.findViewById(R.id.gwc_item_price);
            holder.jianshao = (ImageView) convertView.findViewById(R.id.jianshao);
            holder.num = (TextView) convertView.findViewById(R.id.gwc_number);
            holder.zengjia = (ImageView) convertView.findViewById(R.id.zengjia);
            convertView.setTag(holder);
        } else {
            holder = (ChildViewHolder) convertView.getTag();
        }

        DataActivity_Bean.DatasBean.GoodsCommendListBean goodsCommendListBean = childs[groupPosition][childPosition];
        //价格
        String goods_price = goodsCommendListBean.getGoods_promotion_price();
        holder.price.setText(goods_price);
        //标题
        holder.title.setText(goodsCommendListBean.getGoods_name());
        //复选框的点击事件
        holder.ck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<HashMap<Integer, Boolean>> mapArrayList = childList.get(groupPosition);
                HashMap<Integer, Boolean> hashMap = mapArrayList.get(childPosition);
                hashMap.put(childPosition, !hashMap.get(childPosition));
                //判断二级列表选中的个数
                setGroupCheckBox(groupPosition, childPosition);
                //得到选中的商品数和价格拼成的字符串
                String shop = getShopNumber();
                //查询是否全部选中
                boolean b = selectShopAll();
                //调用自定义接口,把数据传出去
                numberAndIsCheckAll.getNumber(v, shop, b);
                notifyDataSetChanged();
            }
        });

        //设置他的选中状态,根据集合来变化
        ArrayList<HashMap<Integer, Boolean>> arrayList = childList.get(groupPosition);
        HashMap<Integer, Boolean> hashMap = arrayList.get(childPosition);
        holder.ck.setChecked(hashMap.get(childPosition));

        //当个数大于一的时候减少按钮才可以点击,否则不能点击
        int number = Integer.parseInt(holder.num.getText().toString());
        if (number > 1) {
            holder.jianshao.setEnabled(true);
        } else if (number <= 1) {
            holder.jianshao.setEnabled(false);
        }
        //增加数量
        final ChildViewHolder finalHolder = holder;
        holder.zengjia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int number = Integer.parseInt(finalHolder.num.getText().toString());
                number += 1;
                //修改集合中相对应的数量
                List<GWC_Data> gwc_datas = dataList.get(groupPosition);
                gwc_datas.get(childPosition).setNumber(number + "");
                //修改页面的显示数量
                finalHolder.num.setText(number + "");

                //得到选中的商品数和价格拼成的字符串
                String shop = getShopNumber();
                //调用自定义接口,把数据传出去
                numberAndIsCheckAll.getNumber(v, shop, b);
                notifyDataSetChanged();
            }
        });
        holder.jianshao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int number = Integer.parseInt(finalHolder.num.getText().toString());
                if (number > 1) {
                    --number;
                    //修改集合中相对应的数量
                    List<GWC_Data> gwc_datas = dataList.get(groupPosition);
                    gwc_datas.get(childPosition).setNumber(number + "");
                    //修改页面的显示数量
                    finalHolder.num.setText(number + "");
                }

                //得到选中的商品数和价格拼成的字符串
                String shop = getShopNumber();
                //调用自定义接口,把数据传出去
                numberAndIsCheckAll.getNumber(v, shop, b);
                notifyDataSetChanged();
                notifyDataSetChanged();
            }
        });

       /* for (int i = 0; i < dataList.size(); i++) {
            List<GWC_Data> gwc_datas = dataList.get(i);
            for (int y = 0; y < gwc_datas.size(); y++) {
                Logger.e("遍历集合:" + "卖家" + i + "商品" + y + "===" + gwc_datas.get(y).toString());
            }
        }*/
        return convertView;
    }

    public NumberAndIsCheckAll numberAndIsCheckAll;

    public interface NumberAndIsCheckAll {
        void getNumber(View view, String shop, boolean ischecked);
    }

    public void getNumberAndIsCheckAll(NumberAndIsCheckAll numberAndIsCheckAll) {
        this.numberAndIsCheckAll = numberAndIsCheckAll;
    }


    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }


    //点击一级列表,让二级列表全部选中
    public void setChildCheckBox(int index) {
        //遍历存放二级列表数据的集合,设置成一级列表的选中状态
        ArrayList<HashMap<Integer, Boolean>> hashMaps = childList.get(index);
        for (int i = 0; i < hashMaps.size(); i++) {
            HashMap<Integer, Boolean> hashMap = hashMaps.get(i);
            Set<Map.Entry<Integer, Boolean>> set = hashMap.entrySet();
            for (Map.Entry<Integer, Boolean> entry : set) {
                entry.setValue(groupList.get(index).get(index));
            }
        }
        notifyDataSetChanged();
    }


    //点击二级列表的时候,判断是否全选中,如果全选中让一级列表也选中
    public void setGroupCheckBox(int grouIndex, int childIndex) {
        ArrayList<HashMap<Integer, Boolean>> arrayList = childList.get(grouIndex);
        boolean isChecked = true;
        for (int i = 0; i < arrayList.size(); i++) {
            HashMap<Integer, Boolean> hashMap = arrayList.get(i);
            Set<Map.Entry<Integer, Boolean>> set = hashMap.entrySet();

            for (Map.Entry<Integer, Boolean> entry : set) {
                if (!entry.getValue()) {
                    isChecked = false;
                    break;
                }
            }
        }

        HashMap<Integer, Boolean> groupHashMap = groupList.get(grouIndex);
        groupHashMap.put(grouIndex, isChecked);
        notifyDataSetChanged();

    }

    //全选,传的参数判断全选按钮是否选中(true,false),让列表随之改变
    public void setCheckedAll() {
        boolean boo = false;
        //判断是否有没选中,有没选中的话boo=true,在下面的遍历中会全部设置成true
        //如果都是选中状态,boo=false,在下面的遍历中会全部设置成false
        for (int i = 0; i < groupList.size(); i++) {
            HashMap<Integer, Boolean> hashMap = groupList.get(i);
            Set<Map.Entry<Integer, Boolean>> set = hashMap.entrySet();
            for (Map.Entry<Integer, Boolean> entry : set) {
                //如果有没选中的,就把boo设置成true
                //然后下面的那个循环中,把boo设置到value中
                if (!entry.getValue()) {
                    boo = true;
                    break;
                }
            }
        }
        //设置成一级列表的选中状态
        for (int i = 0; i < groupList.size(); i++) {
            HashMap<Integer, Boolean> hashMap = groupList.get(i);
            Set<Map.Entry<Integer, Boolean>> set = hashMap.entrySet();
            for (Map.Entry<Integer, Boolean> entry : set) {
                entry.setValue(boo);
            }
            setChildCheckBox(i);
        }
        notifyDataSetChanged();
    }

    //计算选中的商品个数和总价格
    public String getShopNumber() {
        double Total_price = 0;//总价格
        int Total_number = 0;//总数量
        String str = null;
        for (int i = 0; i < childList.size(); i++) {
            ArrayList<HashMap<Integer, Boolean>> childArrayList = childList.get(i);
            for (int y = 0; y < childArrayList.size(); y++) {
                HashMap<Integer, Boolean> hashMap = childArrayList.get(y);
                Set<Map.Entry<Integer, Boolean>> set = hashMap.entrySet();
                //如果店铺选中,得到总价和数量
                for (Map.Entry<Integer, Boolean> entry : set) {
                    if (entry.getValue()) {
                        //如果选中,得到单价个数量
                        GWC_Data gwc_data = dataList.get(i).get(y);
                        double price = Double.parseDouble(gwc_data.getPrice());
                        int number = Integer.parseInt(gwc_data.getNumber());

                        Total_price += (price * number);
                        Total_number += number;
                    }
                }
            }
        }
        //把总价格和数量拼成字符串
        str = Total_price + "," + Total_number;
        return str;
    }

    //当所有商品全部选中,全选按钮也选中,遍历一级列表,如果一级列表全部选中,则按钮也选中
    public boolean selectShopAll() {
        //默认让全选按钮选中
        boolean boo = true;
        //循环遍历,如果有一个没选中,就设置全选按钮不选中
        for (int i = 0; i < groupList.size(); i++) {
            HashMap<Integer, Boolean> hashMap = groupList.get(i);
            Set<Map.Entry<Integer, Boolean>> set = hashMap.entrySet();
            for (Map.Entry<Integer, Boolean> entry : set) {
                if (!entry.getValue()) {
                    boo = false;
                    break;
                }
            }
        }

        return boo;
    }

    class GroupViewHolder {
        CheckBox ck;
        TextView title;
    }

    class ChildViewHolder {
        CheckBox ck;
        TextView title;
        ImageView img;
        TextView price;
        TextView num;
        ImageView zengjia;
        ImageView jianshao;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值