简单实现 二级列表购物车(固定数据)

效果图:



public class MainActivity extends AppCompatActivity {

    private ExpandableListView listview;
    private MyAdpater adpater;
    private TextView checked_shop;
    private TextView price;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listview = (ExpandableListView) findViewById(R.id.listview);
        adpater = new MyAdpater(this);
        listview.setAdapter(adpater);
        final CheckBox checkAll = (CheckBox) findViewById(R.id.checkAll);
        price = (TextView) findViewById(R.id.price);
        checked_shop = (TextView) findViewById(R.id.checked_shop);
        checkAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置商品全部选中
                adpater.checkAllShop(checkAll.isChecked());
                //计算选中的价格和数量
                String shopPrice = adpater.getShopPrice();
                //判断商品是否全部选中
                boolean b = adpater.selectAll();

                String[] split = shopPrice.split(",");
                price.setText(split[0]);
                checked_shop.setText(split[1]);
                checkAll.setChecked(b);
            }
        });
        adpater.getAdapterData(new MyAdpater.AdapterData() {
            @Override
            public void Data(View v, String str, boolean b) {
                String[] split = str.split(",");
                price.setText(split[0]);
                checked_shop.setText(split[1]);
                checkAll.setChecked(b);
            }
        });

        checkAll.setChecked(adpater.selectAll());
        adpater.notifyDataSetChanged();
    }
}
//适配器
public class MyAdpater extends BaseExpandableListAdapter {
    private Context context;
    private String[] group;
    private String[][] child;
    private HashMap<Integer, Boolean> groupHashMap;
    private List<HashMap<Integer, Boolean>> childList;
    private List<List<Bean>> dataList;

    public MyAdpater(Context context) {
        this.context = context;
        initData();
    }

    private void initData() {
        group = new String[5];
        child = new String[5][];
        groupHashMap = new HashMap<>();
        childList = new ArrayList<>();
        dataList = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            group[i] = "商家" + i;
            groupHashMap.put(i, false);


            String[] strings = new String[3];
            HashMap<Integer, Boolean> map = new HashMap<>();
            ArrayList<Bean> been = new ArrayList<>();
            for (int y = 0; y < 3; y++) {
                strings[y] = "商家" + i + "商品" + y;

                map.put(y, false);

                Bean bean = new Bean("100", "1");
                been.add(bean);
            }

            child[i] = strings;
            childList.add(map);
            dataList.add(been);
        }
    }

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

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

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

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

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

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

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

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        GroupViewHolder holder = null;
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.group_item, null);
            holder = new GroupViewHolder();
            holder.tv = (TextView) convertView.findViewById(R.id.group_tv);
            holder.ck = (CheckBox) convertView.findViewById(R.id.group_ck);
            convertView.setTag(holder);
        } else {
            holder = (GroupViewHolder) convertView.getTag();
        }
        holder.tv.setText(group[groupPosition]);
        holder.ck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                groupHashMap.put(groupPosition, !groupHashMap.get(groupPosition));
                //设置二级列表的选中状态,根据一级列表的状态来改变
                setChildCheckAll();
                //计算选中的价格和数量
                String shopPrice = getShopPrice();
                //判断商品是否全部选中
                boolean b = selectAll();
                adapterData.Data(v, shopPrice, b);

            }

        });

        holder.ck.setChecked(groupHashMap.get(groupPosition));
        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.child_item, null);
            holder = new ChildViewHolder();
            holder.tv = (TextView) convertView.findViewById(R.id.child_tv);
            holder.ck = (CheckBox) convertView.findViewById(R.id.child_ck);
            holder.jianshao = (TextView) convertView.findViewById(R.id.jianshao);
            holder.zengjia = (TextView) convertView.findViewById(R.id.zengjia);
            holder.number = (TextView) convertView.findViewById(R.id.number);
            convertView.setTag(holder);
        } else {
            holder = (ChildViewHolder) convertView.getTag();
        }
        holder.tv.setText(child[groupPosition][childPosition]);
        holder.ck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<Integer, Boolean> hashMap = childList.get(groupPosition);
                hashMap.put(childPosition, !hashMap.get(childPosition));
                //判断二级列表是否全部选中
                ChildisChecked(groupPosition);
                //计算选中的价格和数量
                String shopPrice = getShopPrice();
                //判断商品是否全部选中
                boolean b = selectAll();
                adapterData.Data(v, shopPrice, b);
            }
        });
        final ChildViewHolder finalHolder = holder;
        holder.zengjia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Bean> been = dataList.get(groupPosition);
                String num = finalHolder.number.getText().toString();
                int i = Integer.parseInt(num);
                ++i;
                been.get(childPosition).setNumber(i + "");
                //计算选中的价格和数量
                String shopPrice = getShopPrice();
                //判断商品是否全部选中
                boolean b = selectAll();
                adapterData.Data(v, shopPrice, b);
                notifyDataSetChanged();
            }
        });
        holder.jianshao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<Bean> been = dataList.get(groupPosition);
                String num = finalHolder.number.getText().toString();
                int i = Integer.parseInt(num);
                if (i > 1) {
                    --i;
                }
                been.get(childPosition).setNumber(i + "");
                //计算选中的价格和数量
                String shopPrice = getShopPrice();
                //判断商品是否全部选中
                boolean b = selectAll();
                adapterData.Data(v, shopPrice, b);
                notifyDataSetChanged();
            }
        });

        holder.number.setText(dataList.get(groupPosition).get(childPosition).getNumber().toString());

        holder.ck.setChecked(childList.get(groupPosition).get(childPosition));
        return convertView;
    }


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

    class GroupViewHolder {
        TextView tv;
        CheckBox ck;
    }

    class ChildViewHolder {
        TextView tv;
        CheckBox ck;
        TextView jianshao;
        TextView zengjia;
        TextView number;
    }

    //设置二级列表的选中状态,根据一级列表的状态来改变
    private void setChildCheckAll() {
        for (int i = 0; i < childList.size(); i++) {
            HashMap<Integer, Boolean> integerBooleanHashMap1 = childList.get(i);
            Set<Map.Entry<Integer, Boolean>> entries = integerBooleanHashMap1.entrySet();
            for (Map.Entry<Integer, Boolean> entry : entries) {
                entry.setValue(groupHashMap.get(i));
            }
        }
        notifyDataSetChanged();
    }

    //判断二级列表是否全部选中
    private void ChildisChecked(int groupPosition) {
        boolean ischecked = true;
        HashMap<Integer, Boolean> hashMap = childList.get(groupPosition);
        Set<Map.Entry<Integer, Boolean>> entries = hashMap.entrySet();
        for (Map.Entry<Integer, Boolean> entry : entries) {
            if (!entry.getValue()) {
                ischecked = false;
                break;
            }
        }
        groupHashMap.put(groupPosition, ischecked);
        notifyDataSetChanged();
    }

    //全选
    public void checkAllShop(boolean checked) {
        Set<Map.Entry<Integer, Boolean>> entries = groupHashMap.entrySet();
        for (Map.Entry<Integer, Boolean> entry : entries) {
            entry.setValue(checked);
        }
        //调用让二级列表全选的方法
        setChildCheckAll();
        notifyDataSetChanged();
    }

    //计算价格
    public String getShopPrice() {
        int price = 0;
        int number = 0;
        for (int y = 0; y < childList.size(); y++) {
            HashMap<Integer, Boolean> integerBooleanHashMap1 = childList.get(y);
            Set<Map.Entry<Integer, Boolean>> entries = integerBooleanHashMap1.entrySet();
            for (Map.Entry<Integer, Boolean> entry : entries) {
                if (entry.getValue()) {
                    Bean bean = dataList.get(y).get(entry.getKey());
                    price += Integer.parseInt(bean.getPrice()) * Integer.parseInt(bean.getNumber());
                    number += Integer.parseInt(bean.getNumber());
                }
            }
        }
        return price + "," + number;
    }

    //编辑一级和二级列表,如果全部选中,全选按钮也选中
    public boolean selectAll() {
        boolean isChecked = true;
        for (int y = 0; y < childList.size(); y++) {
            HashMap<Integer, Boolean> hashMap = childList.get(y);
            Set<Map.Entry<Integer, Boolean>> entries = hashMap.entrySet();
            for (Map.Entry<Integer, Boolean> entry : entries) {
                if (!entry.getValue()) {
                    isChecked = false;
                    break;
                }
            }
        }
        return isChecked;
    }

    private AdapterData adapterData;

    public interface AdapterData {
        void Data(View v, String str, boolean b);

    }

    public void getAdapterData(AdapterData adapterData) {
        this.adapterData = adapterData;
    }
}
//保存价格和数量的JavaBean
public class Bean {
    private String price;
    private String number;

    public Bean(String price, String number) {
        this.price = price;
        this.number = number;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}
//MainActivity.xml
<?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">

    <ExpandableListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:groupIndicator="@null"></ExpandableListView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <CheckBox
            android:id="@+id/checkAll"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="15dp"
            android:drawablePadding="5dp"
            android:text="全选"
            android:textColor="#6b6868"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/price"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@id/checkAll"
            android:gravity="center"
            android:text="合计:¥0.00"
            android:textColor="#000000"
            android:textSize="18sp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:background="#ff0000">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:background="#ff0000"
                android:gravity="center"
                android:paddingLeft="30dp"
                android:text="去结算"
                android:textColor="#ffffff"
                android:textSize="22sp" />

            <TextView
                android:id="@+id/checked_shop"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:background="#ff0000"
                android:gravity="center"
                android:paddingRight="30dp"
                android:text="(0)"
                android:textColor="#ffffff"
                android:textSize="13sp" />
        </LinearLayout>

    </RelativeLayout>

</LinearLayout>
//child_item.xml
<?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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <CheckBox
            android:id="@+id/child_ck"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp" />

        <TextView
            android:id="@+id/child_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="10dp">

        <TextView
            android:id="@+id/danjia"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="200dp"
            android:text="100元"
            android:textColor="#ff0000" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true">

            <TextView
                android:id="@+id/jianshao"
                android:layout_width="20dp"
                android:layout_height="30dp"
                android:gravity="center"
                android:text="-"
                android:textSize="20sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/number"
                android:layout_width="wrap_content"
                android:layout_height="30dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:gravity="center"
                android:text="1"
                android:textSize="20sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/zengjia"
                android:layout_width="20dp"
                android:layout_height="30dp"
                android:layout_marginRight="20dp"
                android:gravity="center"
                android:text="+"
                android:textSize="20sp"
                android:textStyle="bold" />
        </LinearLayout>
    </RelativeLayout>


</LinearLayout>
//group_item.xml
<?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">

    <CheckBox
        android:id="@+id/group_ck"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:focusable="false" />

    <TextView
        android:id="@+id/group_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


请求网络数据的二级列表购物车参考GitHub代码:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以回答这个问题。购物车程序可以用列表来存储商品信息和数量,然后用循环来实现添加、删除、修改和结算等功能。具体实现可以参考以下代码: # 定义商品列表 goods = [ {'name': '苹果', 'price': 5}, {'name': '香蕉', 'price': 3}, {'name': '橙子', 'price': 4}, {'name': '西瓜', 'price': 10}, ] # 定义购物车列表 cart = [] # 显示商品列表 print('商品列表:') for i, g in enumerate(goods): print(f'{i+1}. {g["name"]} 价格:{g["price"]}') # 循环操作 while True: # 显示购物车内容 print('购物车:') if len(cart) == : print('空') else: for i, c in enumerate(cart): print(f'{i+1}. {c["name"]} 数量:{c["count"]}') # 显示操作菜单 print('请选择操作:') print('1. 添加商品') print('2. 删除商品') print('3. 修改数量') print('4. 结算') print('5. 退出') choice = input() # 执行操作 if choice == '1': print('请输入商品编号:') index = int(input()) - 1 if index < or index >= len(goods): print('无效的编号') else: g = goods[index] print(f'已添加 {g["name"]} 到购物车') for c in cart: if c['name'] == g['name']: c['count'] += 1 break else: cart.append({'name': g['name'], 'count': 1}) elif choice == '2': print('请输入商品编号:') index = int(input()) - 1 if index < or index >= len(cart): print('无效的编号') else: c = cart[index] print(f'已从购物车删除 {c["name"]}') cart.remove(c) elif choice == '3': print('请输入商品编号:') index = int(input()) - 1 if index < or index >= len(cart): print('无效的编号') else: c = cart[index] print(f'请输入 {c["name"]} 的数量:') count = int(input()) if count <= : print('无效的数量') else: c['count'] = count elif choice == '4': total = for c in cart: for g in goods: if g['name'] == c['name']: total += g['price'] * c['count'] break print(f'总价为 {total} 元') cart.clear() elif choice == '5': break else: print('无效的操作')

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值