二级列表实现购物车功能

导入依赖:

compile 'com.squareup.okio:okio:1.5.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.android.support:mediarouter-v7:25.0.0'
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:recyclerview-v7:25.0.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
shop_activity_layout.xml:

<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>
效果图为:


group_item.xml:

<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" />
效果图为:


child_item.xml:

<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">
  <ImageView
      android:id="@+id/imageShow"
      android:layout_width="30dp"
      android:layout_height="30dp"
      android:src="@mipmap/ic_launcher"/>
    <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>
效果图为:


OkHttpUtils的封装:

public class OkHttpUtils {
    private Handler handler = new Handler();
    public Handler getHandler(){
        return handler;
    }
    //单例
    private static OkHttpUtils okHttpUtils = new OkHttpUtils();
    private OkHttpUtils(){};
    public static OkHttpUtils getInstance(){
        return okHttpUtils;
    }
    private OkHttpClient client;
    //
    private  OkHttpClient getOkHttpClient() {
        synchronized (OkHttpUtils.class) {
            if (client == null) {
                client = new OkHttpClient();
            }
        }
        return client;
    }
    //公用的get请求方法  完成的功能不确定
    public void doGet(String url, Callback callback){
        OkHttpClient okHttpClient = getOkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }
    public  void doPost(String url, Map<String,String> map, Callback callback){
        OkHttpClient okHttpClient = getOkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        //遍历map集合   设置请求体
        for (String mapKey : map.keySet()){
            builder.add(mapKey,map.get(mapKey));
        }
        //设置请求方式
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        //执行请求方式    接口回调
        okHttpClient.newCall(request).enqueue(callback);
    }
    /**
     *1.下载地址
     */
    public  void doDown(String url,Callback callback){
        OkHttpClient okHttpClient = getOkHttpClient();
        Request build = new Request.Builder().url(url).build();
        okHttpClient.newCall(build).enqueue(callback);
    }
}
OnUiCallback的封装:
public abstract  class OnUiCallback implements Callback {
    private Handler handler = OkHttpUtils.getInstance().getHandler();
    public abstract void onFailed(Call call, IOException e);
    public abstract void onSuccess(String result) throws IOException;
    @Override
    public void onFailure(final Call call,final IOException e) {
        //该方式  存在问题  网络请求也跑到了主线程   待解决
        //该方法就是把  线程post到handler所在的线程
        handler.post(new Runnable() {
            @Override
            public void run() {
                onFailed(call, e);
            }
        });
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        final String result = response.body().string();
        //该方式  存在问题  网络请求也跑到了主线程   待解决
        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    onSuccess(result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    }

适配器的实现:

(记的要封装Myapp,OkHttp3Utils,networkutils

public class ShopAdapter 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;
    List<ShopBean.DataBean> class_list;
    public ShopAdapter(Context context) {
        this.context = context;
        initData();
    }

    private void initData() {
        OkHttp3Utils.doGet("http://120.27.23.105/product/getCarts?uid=100", new OnUiCallback(){
        @Override
        public void onFailed(Call call, IOException e) {

        }

        @Override
        public void onSuccess(String result) throws IOException {
            Gson gson = new Gson();
            ShopBean bean2 = gson.fromJson(result, ShopBean.class);


            class_list = bean2.getData();
            group = new String[class_list.size()];
            child = new String[class_list.size()][];
            groupHashMap = new HashMap<>();
            childList = new ArrayList<>();
            dataList = new ArrayList<>();

            for (int i = 0; i < class_list.size(); i++) {
                group[i] = class_list.get(i).getSellerName();
                groupHashMap.put(i, false);

                String[] strings = new String[class_list.get(i).getList().size()];
                HashMap<Integer, Boolean> map = new HashMap<>();
                ArrayList<Bean> been = new ArrayList<>();
                for (int y = 0; y <class_list.get(i).getList().size(); y++) {
                    strings[y] =class_list.get(i).getList() + class_list.get(i).getList().get(y).getImages();
                    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==null?0: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.ctv = (TextView) convertView.findViewById(R.id.child_tv);
            holder.cck = (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);
            holder.cimage = (ImageView) convertView.findViewById(R.id.imageShow);
            convertView.setTag(holder);
        } else {
            holder = (ChildViewHolder) convertView.getTag();
        }
        //请求价格
//        double bargainPrice = class_list.get(groupPosition).getList().get(0).getBargainPrice();
//        holder.danjia.setText((int) bargainPrice);
        //请求题目
        String createtime = class_list.get(groupPosition).getList().get(0).getTitle();
        holder.ctv.setText(createtime);
        //请求图片
        String detailUrl = class_list.get(groupPosition).getList().get(0).getImages();
        String [] temp = null;
        temp = detailUrl.split("\\|");
        Glide.with(context).load(temp[0])
                .into(holder.cimage);

        holder.cck.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.cck.setChecked(childList.get(groupPosition).get(childPosition));
        return convertView;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return false;
    }
    class GroupViewHolder {
        TextView tv;
        CheckBox ck;
    }

    class ChildViewHolder {
//        TextView danjia;
        ImageView cimage;
        TextView ctv;
        CheckBox cck;
        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;
        if(childList!=null){
            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;
    }

}
Activity实现:

public class ShopActivity extends AppCompatActivity {
    private ExpandableListView listview;
    private ShopAdapter adpater;
    private TextView checked_shop;
    private TextView price;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop);
        listview = (ExpandableListView) findViewById(R.id.listview);
        adpater = new ShopAdapter(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 view) {
                //设置商品全部选中
                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 ShopAdapter.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();
    }

}
实现效果图为:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值