购物车之详情页面跳转至购物车

该博客介绍了如何在Android应用中实现在商品详情页面点击后跳转到购物车功能。详细讲解了依赖导入、MVP框架的使用,包括Api接口、HttpUtils类、自定义拦截器MyInterceptor类和接口回调类OnNetListener的实现。同时展示了Model层、DetailsService接口类和DetailsModel类的代码实现,以及如何处理商品数据和UI交互,如CheckBox的点击事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


首先依赖导入:

compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.google.code.gson:gson:2.8.2'
compile 'io.github.openfeign:feign-gson:9.5.1'
compile 'com.android.support:recyclerview-v7:24.0.0-alpha1'
compile 'com.github.bumptech.glide:glide:3.7.0'

之后MVP框架:

net包

Api接口类:

public static String DETAIL = "https://www.zhaoapi.cn/product/getProductDetail";   //详情接口
public static String ADDCART = "https://www.zhaoapi.cn/product/getCarts";           //添加购物车
public static String GETCART = "https://www.zhaoapi.cn/product/addCart";            //获得展示购物车(二级列表 需传uid,pid)

HttpUtils类:

package com.bwie.detailsdemo.net;

import java.util.Map;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by admin on 2017/12/18.
 */

public class HttpUtils {

    private static volatile HttpUtils httpUtils;
    private final OkHttpClient client;

    private HttpUtils(){
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        client = new OkHttpClient.Builder()
                .addInterceptor(new MyInterceptor())
                .build();
    }

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

    public void doGet(String url, Callback callback){
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(callback);
    }

    public void doPost(String url, Map<String, String> params, Callback callback){
        if (params == null) {
            throw new RuntimeException("参数为空了");
        }
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder().url(url).post(formBody).build();
        client.newCall(request).enqueue(callback);
    }
}

自定义拦截器MyInterceptor类:

package com.bwie.detailsdemo.net;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by admin on 2017/12/18.
 */

public class MyInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (request.method().equals("GET")){
            String url = request.url().url().toString();
            url += "&source=android";
            Request newRequest = request.newBuilder().url(url).build();
            return chain.proceed(newRequest);
        }else {
            FormBody formBody = (FormBody) request.body();
            FormBody.Builder builder = new FormBody.Builder();
            for (int i = 0; i <formBody.size(); i++){
                builder.add(formBody.name(i), formBody.value(i));
            }
            builder.add("source", "android");
            FormBody newFormBody = builder.build();
            Request newRequest = request.newBuilder().url(request.url().url().toString()).post(newFormBody).build();
            return chain.proceed(newRequest);
        }
    }
}

接口回调类OnNetListener:

package com.bwie.detailsdemo.net;

/**
 * Created by admin on 2017/12/18.
 */

public interface OnNetListener<T> {

    public void onSuccess(T t);

    public void onFailure(Exception e);
}

模块展示代码:

详情页面MVP:

Bean包

DetailBean


package com.example.peng.goodscard_1510d.bean;


/**
 * Created by peng on 2017/12/14.
 */


public class DetailsBean {


    /**
     * msg :
     * seller : {"description":"我是商家15","icon":"http://120.27.23.105/images/icon.png","name":"商家15","productNums":999,"score":5,"sellerid":15}
     * code : 0
     * data : {"bargainPrice":11800,"createtime":"2017-10-03T23:53:28","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","itemtype":0,"pid":71,"price":32999,"pscid":40,"salenum":4242,"sellerid":15,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}
     */


    private String msg;
    private SellerBean seller;
    private String code;
    private DataBean data;


    public String getMsg() {
        return msg;
    }


    public void setMsg(String msg) {
        this.msg = msg;
    }


    public SellerBean getSeller() {
        return seller;
    }


    public void setSeller(SellerBean seller) {
        this.seller = seller;
    }


    public String getCode() {
        return code;
    }


    public void setCode(String code) {
        this.code = code;
    }


    public DataBean getData() {
        return data;
    }


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


    public static class SellerBean {
        /**
         * description : 我是商家15
         * icon : http://120.27.23.105/images/icon.png
         * name : 商家15
         * productNums : 999
         * score : 5.0
         * sellerid : 15
         */


        private String description;
        private String icon;
        private String name;
        private int productNums;
        private double score;
        private int sellerid;


        public String getDescription() {
            return description;
        }


        public void setDescription(String description) {
            this.description = description;
        }


        public String getIcon() {
            return icon;
        }


        public void setIcon(String icon) {
            this.icon = icon;
        }


        public String getName() {
            return name;
        }


        public void setName(String name) {
            this.name = name;
        }


        public int getProductNums() {
            return productNums;
        }


        public void setProductNums(int productNums) {
            this.productNums = productNums;
        }


        public double getScore() {
            return score;
        }


        public void setScore(double score) {
            this.score = score;
        }


        public int getSellerid() {
            return sellerid;
        }


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


    public static class DataBean {
        /**
         * bargainPrice : 11800.0
         * createtime : 2017-10-03T23:53:28
         * detailUrl : https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1
         * images : https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg
         * itemtype : 0
         * pid : 71
         * price : 32999.0
         * pscid : 40
         * salenum : 4242
         * sellerid : 15
         * subhead : 购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)
         * title : 全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G
         */


        private double bargainPrice;
        private String createtime;
        private String detailUrl;
        private String images;
        private int itemtype;
        private int pid;
        private double price;
        private int pscid;
        private int salenum;
        private int sellerid;
        private String subhead;
        private String title;


        public double getBargainPrice() {
            return bargainPrice;
        }


        public void setBargainPrice(double 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 getItemtype() {
            return itemtype;
        }


        public void setItemtype(int itemtype) {
            this.itemtype = itemtype;
        }


        public int getPid() {
            return pid;
        }


        public void setPid(int pid) {
            this.pid = pid;
        }


        public double getPrice() {
            return price;
        }


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


        public int getPscid() {
            return pscid;
        }


        public void setPscid(int pscid) {
            this.pscid = pscid;
        }


        public int getSalenum() {
            return salenum;
        }


        public void setSalenum(int salenum) {
            this.salenum = salenum;
        }


        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;
        }
    }
}

Model层

DetailsService接口类

package com.example.peng.goodscard_1510d.model;


import com.example.peng.goodscard_1510d.bean.DetailsBean;
import com.example.peng.goodscard_1510d.net.OnNetListener;


import java.util.Map;


/**
 * Created by peng on 2017/12/14.
 */


public interface DetailsService {
    void getProductDetail(Map<String, String> params, OnNetListener<DetailsBean> onNetListener);
}


DetailsModel类


package com.example.peng.goodscard_1510d.model;


import android.os.Handler;
import android.os.Looper;


import com.example.peng.goodscard_1510d.bean.DetailsBean;
import com.example.peng.goodscard_1510d.net.Api;
import com.example.peng.goodscard_1510d.net.OkHttpUtils;
import com.example.peng.goodscard_1510d.net.OnNetListener;
import com.google.gson.Gson;


import java.io.IOException;
import java.util.Map;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * Created by peng on 2017/12/14.
 */


public class DetailsModel implements DetailsService {
    private Handler handler = new Handler(Looper.getMainLooper());


    @Override
    public void getProductDetail(Map<String, String> params, final OnNetListener<DetailsBean> onNetListener) {
        OkHttpUtils.getOkHttpUtils().doPost(Api.str1, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {


            }


            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final DetailsBean detailsBean = new Gson().fromJson(string, DetailsBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onSuccess(detailsBean);
                    }
                });
            }
        });
    }
}


presenter类

DetailsPresenter类


package com.example.peng.goodscard_1510d.presenter;


import com.example.peng.goodscard_1510d.bean.DetailsBean;
import com.example.peng.goodscard_1510d.model.DetailsModel;
import com.example.peng.goodscard_1510d.model.DetailsService;
import com.example.peng.goodscard_1510d.net.OnNetListener;
import com.example.peng.goodscard_1510d.view.IMainListener;


import java.util.HashMap;
import java.util.Map;


/**
 * Created by peng on 2017/12/14.
 */


public class DetailsPresenter {
    private IMainListener iMainListener;
    private DetailsService detailsService;


    public DetailsPresenter(IMainListener iMainListener) {
        this.iMainListener = iMainListener;
        detailsService = new DetailsModel();
    }


    public void dettach() {
        iMainListener = null;
    }


    public void getProductDetail() {
        Map<String, String> params = new HashMap<>();
        params.put("pid", "71");
        detailsService.getProductDetail(params, new OnNetListener<DetailsBean>() {
            @Override
            public void onSuccess(DetailsBean detailsBean) {
                if (iMainListener != null) {
                    iMainListener.show(detailsBean);
                }
            }


            @Override
            public void onFailure(Exception e) {


            }
        });
    }
}


view层

IMainListener接口类


package com.example.peng.goodscard_1510d.view;


import com.example.peng.goodscard_1510d.bean.DetailsBean;


/**
 * Created by peng on 2017/12/14.
 */


public interface IMainListener {
    void show(DetailsBean detailsBean);


    void show(String str);
}




MainActivity类

package com.example.peng.goodscard_1510d.view;


import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextPaint;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.example.peng.goodscard_1510d.R;
import com.example.peng.goodscard_1510d.bean.DetailsBean;
import com.example.peng.goodscard_1510d.presenter.AddCartPresenter;
import com.example.peng.goodscard_1510d.presenter.DetailsPresenter;


/**
 * 详情页面
 */
public class MainActivity extends AppCompatActivity implements IMainListener, View.OnClickListener {


    private DetailsPresenter detailsPresenter;
    private ImageView mIv;
    private TextView mTvBargainPrice;
    private TextView mTvPrice;
    /**
     * 购物车
     */
    private TextView mTvCart;
    /**
     * 加入购物车
     */
    private TextView mTvAddCart;
    private AddCartPresenter addCartPresenter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        detailsPresenter = new DetailsPresenter(this);
        addCartPresenter = new AddCartPresenter(this);
        detailsPresenter.getProductDetail();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        detailsPresenter.dettach();
        addCartPresenter.dettach();
    }


    @Override
    public void show(DetailsBean detailsBean) {
        String images = detailsBean.getData().getImages();
        String[] split = images.split("\\|");
        Glide.with(this).load(split[0]).into(mIv);
        TextPaint paint = mTvBargainPrice.getPaint();
        paint.setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        mTvBargainPrice.setText("原价:" + detailsBean.getData().getBargainPrice());
        mTvPrice.setText("优惠价:" + detailsBean.getData().getPrice());
    }


    @Override
    public void show(String str) {
        Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
    }


    private void initView() {
        mIv = (ImageView) findViewById(R.id.iv);
        mTvBargainPrice = (TextView) findViewById(R.id.tvBargainPrice);
        mTvPrice = (TextView) findViewById(R.id.tvPrice);
        mTvCart = (TextView) findViewById(R.id.tvCart);
        mTvAddCart = (TextView) findViewById(R.id.tvAddCart);
        mTvCart.setOnClickListener(this);
        mTvAddCart.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tvCart:
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
                break;
            case R.id.tvAddCart:
                addCartPresenter.addCart();
                break;
        }
    }
}


activity_main布局


<?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"
    tools:context="com.example.peng.goodscard_1510d.view.MainActivity">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#ff3660"
        android:gravity="center"
        android:text="商品详情"
        android:textColor="#ffffff"
        android:textSize="25sp" />


    <ImageView
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="400dp" />


    <TextView
        android:id="@+id/tvBargainPrice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp" />


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


    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"></View>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp">


        <TextView
            android:id="@+id/tvCart"
            android:layout_width="0dp"
            android:background="#33000000"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="购物车" />


        <TextView
            android:id="@+id/tvAddCart"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#33000000"
            android:gravity="center"
            android:text="加入购物车" />
    </LinearLayout>
</LinearLayout>


-----------------------------------------------------------------------------------------------------------------------------------------------

添加购物车

Bean:

AddCartBean类:



package com.example.peng.goodscard_1510d.bean;


/**
 * Created by peng on 2017/12/14.
 */


public class AddCartBean {


    /**
     * msg : 加购成功
     * code : 0
     */


    private String msg;
    private String code;


    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;
    }
}


Model层

AddCartService接口类:


package com.example.peng.goodscard_1510d.model;


import com.example.peng.goodscard_1510d.bean.AddCartBean;
import com.example.peng.goodscard_1510d.net.OnNetListener;


import java.util.Map;


/**
 * Created by peng on 2017/12/14.
 */


public interface AddCartService {
    void addCart(Map<String, String> params, OnNetListener<AddCartBean> onNetListener);
}


AddCartModel类:


package com.example.peng.goodscard_1510d.model;


import android.os.Handler;
import android.os.Looper;


import com.example.peng.goodscard_1510d.bean.AddCartBean;
import com.example.peng.goodscard_1510d.bean.DetailsBean;
import com.example.peng.goodscard_1510d.net.Api;
import com.example.peng.goodscard_1510d.net.OkHttpUtils;
import com.example.peng.goodscard_1510d.net.OnNetListener;
import com.google.gson.Gson;


import java.io.IOException;
import java.util.Map;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * Created by peng on 2017/12/14.
 */


public class AddCartModel implements AddCartService {
    private Handler handler = new Handler(Looper.getMainLooper());


    @Override
    public void addCart(Map<String, String> params, final OnNetListener<AddCartBean> onNetListener) {
        OkHttpUtils.getOkHttpUtils().doPost(Api.str1, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {


            }


            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final AddCartBean addCartBean = new Gson().fromJson(string, AddCartBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onSuccess(addCartBean);
                    }
                });
            }
        });
    }
}


presenter层:

AddCartPresenter类:


package com.example.peng.goodscard_1510d.presenter;


import com.example.peng.goodscard_1510d.bean.AddCartBean;
import com.example.peng.goodscard_1510d.model.AddCartModel;
import com.example.peng.goodscard_1510d.model.AddCartService;
import com.example.peng.goodscard_1510d.net.OnNetListener;
import com.example.peng.goodscard_1510d.view.IMainListener;


import java.util.HashMap;
import java.util.Map;


/**
 * Created by peng on 2017/12/14.
 */


public class AddCartPresenter {
    private IMainListener iMainListener;
    private AddCartService addCartService;


    public AddCartPresenter(IMainListener iMainListener) {
        this.iMainListener = iMainListener;
        addCartService = new AddCartModel();
    }


    public void dettach() {
        iMainListener = null;
    }


    public void addCart() {
        Map<String, String> params = new HashMap<>();
        params.put("pid", "71");
        params.put("uid", "39");
        addCartService.addCart(params, new OnNetListener<AddCartBean>() {
            @Override
            public void onSuccess(AddCartBean addCartBean) {
                if (iMainListener != null) {
                    iMainListener.show(addCartBean.getCode().equals("0") ? "添加成功了" : "添加失败了");
                }
            }


            @Override
            public void onFailure(Exception e) {


            }
        });
    }
}


View类呢跟详情页面一样都是MainActivity见上面


--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

展示获得购物车

Bean类:

GetCartBean类:(二级列表)


package com.example.peng.goodscard_1510d.bean;


import java.util.List;


/**
 * Created by peng on 2017/12/14.
 */


public class GetCartBean {


    /**
     * msg : 请求成功
     * code : 0
     * data : [{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":2,"pid":9,"price":78.99,"pscid":1,"selected":0,"sellerid":2,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家2","sellerid":"2"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":3,"pid":10,"price":555.55,"pscid":1,"selected":0,"sellerid":3,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家3","sellerid":"3"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":11,"price":8989,"pscid":1,"selected":0,"sellerid":4,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家4","sellerid":"4"},{"list":[{"bargainPrice":11800,"createtime":"2017-10-14T21:38:26","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","num":1,"pid":69,"price":16999,"pscid":40,"selected":0,"sellerid":13,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家13","sellerid":"13"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":13,"pid":1,"price":118,"pscid":1,"selected":0,"sellerid":17,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家17","sellerid":"17"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":2,"price":299,"pscid":1,"selected":0,"sellerid":18,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家18","sellerid":"18"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":5,"price":88.99,"pscid":1,"selected":0,"sellerid":21,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家21","sellerid":"21"},{"list":[{"bargainPrice":111.99,"createtime":"2017-10-14T21:39:05","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":1,"pid":7,"price":120.01,"pscid":1,"selected":0,"sellerid":23,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}],"sellerName":"商家23","sellerid":"23"}]
     */


    private String msg;
    private String code;
    private List<DataBean> 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 List<DataBean> getData() {
        return data;
    }


    public void setData(List<DataBean> data) {
        this.data = data;
    }


    public static class DataBean {
        /**
         * list : [{"bargainPrice":111.99,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg","num":2,"pid":9,"price":78.99,"pscid":1,"selected":0,"sellerid":2,"subhead":"每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下","title":"北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g"}]
         * sellerName : 商家2
         * sellerid : 2
         */
        private boolean checked;
        private String sellerName;
        private String sellerid;
        private List<ListBean> list;


        public boolean isChecked() {
            return checked;
        }


        public void setChecked(boolean checked) {
            this.checked = checked;
        }


        public String getSellerName() {
            return sellerName;
        }


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


        public String getSellerid() {
            return sellerid;
        }


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


        public List<ListBean> getList() {
            return list;
        }


        public void setList(List<ListBean> list) {
            this.list = list;
        }


        public static class ListBean {
            /**
             * bargainPrice : 111.99
             * createtime : 2017-10-14T21:48:08
             * detailUrl : https://item.m.jd.com/product/4719303.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends
             * images : https://m.360buyimg.com/n0/jfs/t9004/210/1160833155/647627/ad6be059/59b4f4e1N9a2b1532.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7504/338/63721388/491286/f5957f53/598e95f1N7f2adb87.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7441/10/64242474/419246/adb30a7d/598e95fbNd989ba0a.jpg!q70.jpg
             * num : 2
             * pid : 9
             * price : 78.99
             * pscid : 1
             * selected : 0
             * sellerid : 2
             * subhead : 每个中秋都不能简单,无论身在何处,你总需要一块饼让生活更圆满,京东月饼让爱更圆满京东自营,闪电配送,更多惊喜,快用手指戳一下
             * title : 北京稻香村 稻香村中秋节月饼 老北京月饼礼盒655g
             */
            private boolean checked;
            private int count = 1;
            private double bargainPrice;
            private String createtime;
            private String detailUrl;
            private String images;
            private int num;
            private int pid;
            private double price;
            private int pscid;
            private int selected;
            private int sellerid;
            private String subhead;
            private String title;


            public boolean isChecked() {
                return checked;
            }


            public void setChecked(boolean checked) {
                this.checked = checked;
            }


            public int getCount() {
                return count;
            }


            public void setCount(int count) {
                this.count = count;
            }


            public double getBargainPrice() {
                return bargainPrice;
            }


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


            public void setPrice(double 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;
            }
        }
    }
}


Model层:

GetCartService接口类:


package com.example.peng.goodscard_1510d.model;


import com.example.peng.goodscard_1510d.bean.AddCartBean;
import com.example.peng.goodscard_1510d.bean.GetCartBean;
import com.example.peng.goodscard_1510d.net.OnNetListener;


import java.util.Map;


/**
 * Created by peng on 2017/12/14.
 */


public interface GetCartService {
    void getCart(Map<String, String> params, OnNetListener<GetCartBean> onNetListener);
}


GetCartModel类:


package com.example.peng.goodscard_1510d.model;


import android.os.Handler;
import android.os.Looper;


import com.example.peng.goodscard_1510d.bean.DetailsBean;
import com.example.peng.goodscard_1510d.bean.GetCartBean;
import com.example.peng.goodscard_1510d.net.Api;
import com.example.peng.goodscard_1510d.net.OkHttpUtils;
import com.example.peng.goodscard_1510d.net.OnNetListener;
import com.google.gson.Gson;


import java.io.IOException;
import java.util.Map;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * Created by peng on 2017/12/14.
 */


public class GetCartModel implements GetCartService {
    private Handler handler = new Handler(Looper.getMainLooper());


    @Override
    public void getCart(Map<String, String> params, final OnNetListener<GetCartBean> onNetListener) {
        OkHttpUtils.getOkHttpUtils().doPost(Api.str2, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {


            }


            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final GetCartBean getCartBean = new Gson().fromJson(string, GetCartBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onSuccess(getCartBean);
                    }
                });
            }
        });
    }
}


presenter类:

GetCartPresenter类:


package com.example.peng.goodscard_1510d.presenter;


import com.example.peng.goodscard_1510d.bean.GetCartBean;
import com.example.peng.goodscard_1510d.model.GetCartModel;
import com.example.peng.goodscard_1510d.model.GetCartService;
import com.example.peng.goodscard_1510d.net.OnNetListener;
import com.example.peng.goodscard_1510d.view.ISecondListener;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by peng on 2017/12/14.
 */


public class GetCartPresenter {
    private ISecondListener iSecondListener;
    private final GetCartService getCartService;


    public GetCartPresenter(ISecondListener iSecondListener) {
        this.iSecondListener = iSecondListener;
        getCartService = new GetCartModel();
    }


    public void dettach() {
        iSecondListener = null;
    }


    public void getCart() {
        Map<String, String> params = new HashMap<>();
        params.put("uid", "1234");
        params.put("pid", "71");
        getCartService.getCart(params, new OnNetListener<GetCartBean>() {
            @Override
            public void onSuccess(GetCartBean getCartBean) {
                if (iSecondListener != null) {
                    List<GetCartBean.DataBean> group = getCartBean.getData();
                    List<List<GetCartBean.DataBean.ListBean>> child = new ArrayList<>();
                    for (int i = 0; i < group.size(); i++) {
                        child.add(group.get(i).getList());
                    }
                    iSecondListener.show(group, child);
                }
            }


            @Override
            public void onFailure(Exception e) {


            }
        });
    }
}


View层

ISecondListener接口类:


package com.example.peng.goodscard_1510d.view;


import com.example.peng.goodscard_1510d.bean.GetCartBean;


import java.util.List;


/**
 * Created by peng on 2017/12/14.
 */


public interface ISecondListener {
    void show(List<GetCartBean.DataBean> group, List<List<GetCartBean.DataBean.ListBean>> child);
}


SecondActivity类:


package com.example.peng.goodscard_1510d.view;


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;


import com.example.peng.goodscard_1510d.R;
import com.example.peng.goodscard_1510d.adapter.ElvAdapter;
import com.example.peng.goodscard_1510d.bean.GetCartBean;
import com.example.peng.goodscard_1510d.bean.PriceAndCount;
import com.example.peng.goodscard_1510d.presenter.GetCartPresenter;


import java.util.List;


public class SecondActivity extends AppCompatActivity implements ISecondListener {


    private GetCartPresenter getCartPresenter;
    private ExpandableListView mElv;
    /**
     * 全选
     */
    private CheckBox mCb;
    /**
     * 合计:
     */
    private TextView mTvTotal;
    /**
     * 去结算(0)
     */
    private TextView mTvCount;
    private ElvAdapter elvAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        initView();
        getCartPresenter = new GetCartPresenter(this);
        getCartPresenter.getCart();


        mCb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                elvAdapter.AllOrNone(mCb.isChecked());
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        getCartPresenter.dettach();
    }


    @Override
    public void show(List<GetCartBean.DataBean> group, List<List<GetCartBean.DataBean.ListBean>> child) {
        elvAdapter = new ElvAdapter(this, group, child);
        mElv.setGroupIndicator(null);
        mElv.setAdapter(elvAdapter);
        for (int i = 0; i < group.size(); i++) {
            mElv.expandGroup(i);


        }
    }


    private void initView() {
        mElv = (ExpandableListView) findViewById(R.id.elv);
        mCb = (CheckBox) findViewById(R.id.cb);
        mTvTotal = (TextView) findViewById(R.id.tvTotal);
        mTvCount = (TextView) findViewById(R.id.tvCount);
    }


    public void setPriceAndCount(PriceAndCount priceAndCount) {
        mTvTotal.setText("合计:" + priceAndCount.getPrice());
        mTvCount.setText("去结算(" + priceAndCount.getCount() + ")");
    }


    public void setAllChecked(boolean bool) {
        mCb.setChecked(bool);
    }
}


activity_second布局:


<?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"
    tools:context="bwie.com.a1510dproject.view.GoodsCardActivity">


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


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


        <CheckBox
            android:id="@+id/cb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="全选" />


        <TextView
            android:id="@+id/tvTotal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="15dp"
            android:layout_toRightOf="@id/cb"
            android:text="合计:" />


        <TextView
            android:id="@+id/tvCount"
            android:layout_width="100dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="#ff0000"
            android:gravity="center"
            android:text="去结算(0)"
            android:textColor="#ffffff" />
    </RelativeLayout>
</LinearLayout>


二级列表布局:

一级列表:


<?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="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">


    <CheckBox
        android:id="@+id/cbGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    <TextView
        android:id="@+id/tvGroup"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center_vertical" />
</LinearLayout>


二级列表:


<?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="120dp"
    android:descendantFocusability="blocksDescendants"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:paddingLeft="50dp">


    <CheckBox
        android:id="@+id/cbChild"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    <ImageView
        android:id="@+id/iv"
        android:layout_width="100dp"
        android:layout_height="100dp" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">


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


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


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


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal">


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


            <ImageView
                android:layout_marginLeft="10dp"
                android:id="@+id/ivDel"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:background="@drawable/iv_del" />


            <TextView
                android:id="@+id/tvNum"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="25sp"
                android:layout_marginLeft="3dp"
                android:layout_marginRight="3dp"
                android:text="1"/>


            <ImageView
                android:id="@+id/ivAdd"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:background="@drawable/iv_add" />
        </LinearLayout>
    </LinearLayout>


    <Button
        android:id="@+id/btDel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除" />
</LinearLayout>


适配器:

ElvAdapter:


package com.example.peng.goodscard_1510d.adapter;


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.example.peng.goodscard_1510d.R;
import com.example.peng.goodscard_1510d.bean.GetCartBean;
import com.example.peng.goodscard_1510d.bean.PriceAndCount;
import com.example.peng.goodscard_1510d.view.SecondActivity;


import java.util.List;


/**
 * Created by peng on 2017/12/14.
 */


public class ElvAdapter extends BaseExpandableListAdapter {
    private Context context;
    private List<GetCartBean.DataBean> group;
    private List<List<GetCartBean.DataBean.ListBean>> child;
    private final LayoutInflater inflater;


    public ElvAdapter(Context context, List<GetCartBean.DataBean> group, List<List<GetCartBean.DataBean.ListBean>> child) {
        this.context = context;
        this.group = group;
        this.child = child;
        inflater = LayoutInflater.from(context);
    }


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


    @Override
    public int getChildrenCount(int groupPosition) {
        return child.get(groupPosition).size();
    }


    @Override
    public Object getGroup(int groupPosition) {
        return group.get(groupPosition);
    }


    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return child.get(groupPosition).get(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) {
        View view;
        final GroupViewHolder holder;
        if (convertView == null) {
            view = inflater.inflate(R.layout.elv_group, null);
            holder = new GroupViewHolder();
            holder.tv = view.findViewById(R.id.tvGroup);
            holder.cbGroup = view.findViewById(R.id.cbGroup);
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (GroupViewHolder) view.getTag();
        }
        final GetCartBean.DataBean dataBean = group.get(groupPosition);
        holder.tv.setText(dataBean.getSellerName());
        holder.cbGroup.setChecked(dataBean.isChecked());


        holder.cbGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //需要改变三个checkbox的状态值
                //1.一级列表的checkbox状态值
                dataBean.setChecked(holder.cbGroup.isChecked());
                //2.二级列表的checkbox状态值
                setChildrenCb(groupPosition, holder.cbGroup.isChecked());
                //3.全选的checkbox状态值
                ((SecondActivity) context).setAllChecked(isAllGroupCbChecked());
                //计算钱和数量并显示
                setPriceAndCount();
                //刷新界面
                notifyDataSetChanged();
            }
        });
        return view;
    }


    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, final View convertView, ViewGroup parent) {
        View view;
        final ChildViewHolder holder;
        if (convertView == null) {
            view = inflater.inflate(R.layout.elv_child, null);
            holder = new ChildViewHolder();
            holder.iv = view.findViewById(R.id.iv);
            holder.tvTitle = view.findViewById(R.id.tvTitle);
            holder.tvSubhead = view.findViewById(R.id.tvSubhead);
            holder.tvPrice = view.findViewById(R.id.tvPrice);
            holder.cbChild = view.findViewById(R.id.cbChild);
            holder.btDel = view.findViewById(R.id.btDel);
            holder.tvNum = view.findViewById(R.id.tvNum);
            holder.ivDel = view.findViewById(R.id.ivDel);
            holder.ivAdd = view.findViewById(R.id.ivAdd);
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (ChildViewHolder) view.getTag();
        }


        final GetCartBean.DataBean.ListBean listBean = child.get(groupPosition).get(childPosition);
        String images = listBean.getImages();
        Glide.with(context).load(images.split("\\|")[0]).into(holder.iv);
        holder.tvTitle.setText(listBean.getTitle());
        holder.cbChild.setChecked(child.get(groupPosition).get(childPosition).isChecked());
        holder.tvSubhead.setText(listBean.getSubhead());
        holder.tvPrice.setText(listBean.getPrice() + "元");
        holder.tvNum.setText(listBean.getCount() + "");
        //给checkbox设置点击事件
        holder.cbChild.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //需要改变三个checkbox的状态值
                //1.二级列表的checkbox状态值
                listBean.setChecked(holder.cbChild.isChecked());
                //2.一级列表的checkbox状态值
                group.get(groupPosition).setChecked(isAllChildCbChecked(groupPosition));
                //3.全选的checkbox状态值
                ((SecondActivity) context).setAllChecked(isAllGroupCbChecked());
                //计算钱和数量并显示
                setPriceAndCount();
                //刷新界面
                notifyDataSetChanged();
            }
        });


        holder.ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取目前显示的值
                int count = listBean.getCount();
                count++;
                //改变JavaBean里的状态值
                listBean.setCount(count);
                //计算钱和数量并显示
                setPriceAndCount();
                //刷新列表
                notifyDataSetChanged();
            }
        });
        holder.ivDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取目前显示的值
                int count = listBean.getCount();
                if (count <= 1) {
                    count = 1;
                } else {
                    count--;
                }
                //改变JavaBean里的状态值
                listBean.setCount(count);
                //计算钱和数量并显示
                setPriceAndCount();
                //刷新列表
                notifyDataSetChanged();
            }
        });


        holder.btDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //其实就是删除集合
                List<GetCartBean.DataBean.ListBean> listBeans = child.get(groupPosition);
                if (listBeans.size() > 0) {
                    listBeans.remove(childPosition);
                }
                if (listBeans.size() == 0) {
                    child.remove(groupPosition);
                    group.remove(groupPosition);
                }
                //计算钱和数量并显示
                setPriceAndCount();
                //改变全选状态
                ((SecondActivity) context).setAllChecked(isAllGroupCbChecked());
                //刷新列表
                notifyDataSetChanged();
            }
        });
        return view;
    }


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


    class GroupViewHolder {
        TextView tv;
        CheckBox cbGroup;
    }


    class ChildViewHolder {
        ImageView iv;
        TextView tvTitle;
        TextView tvSubhead;
        TextView tvPrice;
        CheckBox cbChild;
        Button btDel;
        TextView tvNum;
        ImageView ivDel;
        ImageView ivAdd;
    }


    /**
     * 设置一级列表对应的二级列表checkbox状态
     *
     * @param groupPosition
     * @param bool
     */
    private void setChildrenCb(int groupPosition, boolean bool) {
        List<GetCartBean.DataBean.ListBean> listBeans = child.get(groupPosition);
        for (int i = 0; i < listBeans.size(); i++) {
            listBeans.get(i).setChecked(bool);
        }
    }


    /**
     * 判断一级列表checkbox状态
     *
     * @return
     */
    private boolean isAllGroupCbChecked() {
        if (group.size() == 0) {
            return false;
        }
        for (int i = 0; i < group.size(); i++) {
            if (!group.get(i).isChecked()) {
                return false;
            }
        }
        return true;
    }


    /**
     * 判断二级列表checkbox状态
     *
     * @return
     */
    private boolean isAllChildCbChecked(int groupPosition) {
        List<GetCartBean.DataBean.ListBean> listBeans = child.get(groupPosition);
        for (int i = 0; i < listBeans.size(); i++) {
            if (!listBeans.get(i).isChecked()) {
                return false;
            }
        }
        return true;
    }


    /**
     * 设置钱和数量
     */
    private void setPriceAndCount() {
        ((SecondActivity) context).setPriceAndCount(compute());
    }


    /**
     * 计算钱和数量
     */
    private PriceAndCount compute() {
        double price = 0;
        int count = 0;
        for (int i = 0; i < group.size(); i++) {
            List<GetCartBean.DataBean.ListBean> listBeans = child.get(i);
            for (int j = 0; j < listBeans.size(); j++) {
                if (listBeans.get(j).isChecked()) {
                    price += listBeans.get(j).getPrice() * listBeans.get(j).getCount();
                    count += listBeans.get(j).getCount();
                }
            }
        }
        return new PriceAndCount(price, count);
    }


    /**
     * 全选或者全不选
     *
     * @param bool
     */
    public void AllOrNone(boolean bool) {
        for (int i = 0; i < group.size(); i++) {
            group.get(i).setChecked(bool);
            setChildrenCb(i, bool);
        }
        setPriceAndCount();
        notifyDataSetChanged();
    }
}



drawable目录下的加 减图片











### 购物车页面跳转的实现方法 在前端开发中,实现购物车页面跳转的功能通常依赖于路由管理工具或直接使用浏览器的 `window.location` 对象。以下是几种常见的实现方法: #### 1. 使用 `window.location.href` 最简单的方式是通过修改 `window.location.href` 的值来实现页面跳转。这种方法适用于传统的多页应用(MPA),其中每个页面都是独立的 HTML 文件。 ```javascript function goToCartPage() { window.location.href = "/cart.html"; // 替换为实际的购物车页面路径 } ``` #### 2. 使用前端路由(SPA) 对于单页应用(SPA),可以使用前端路由库(如 React Router、Vue Router 或 Angular Router)来实现页面跳转。以下是一些示例代码: - **React Router 示例** ```javascript import { useNavigate } from 'react-router-dom'; function CartButton() { const navigate = useNavigate(); const handleCartClick = () => { navigate('/cart'); // 替换为实际的购物车路由路径 }; return <button onClick={handleCartClick}>Go to Cart</button>; } ``` - **Vue Router 示例** ```javascript <template> <button @click="goToCart">Go to Cart</button> </template> <script> export default { methods: { goToCart() { this.$router.push({ path: '/cart' }); // 替换为实际的购物车路由路径 } } }; </script> ``` - **Angular Router 示例** ```typescript import { Router } from '@angular/router'; export class CartComponent { constructor(private router: Router) {} goToCart() { this.router.navigate(['/cart']); // 替换为实际的购物车路由路径 } } ``` #### 3. 使用事件监听器 如果需要在特定事件(如点击按钮)触发时跳转购物车页面,可以通过绑定事件监听器实现。 ```javascript document.getElementById('go-to-cart').addEventListener('click', function() { window.location.href = "/cart.html"; // 替换为实际的购物车页面路径 }); ``` #### 4. 考虑用户体验 在实现页面跳转时,还应考虑用户体验。例如,在跳转前可以提示用户是否保存当前操作的结果[^1]。此外,确保页面加载速度快且购物车数据能够正确同步。 ```javascript function confirmAndGoToCart() { if (confirm("Are you sure you want to go to the cart page?")) { window.location.href = "/cart.html"; // 替换为实际的购物车页面路径 } } ``` ### 注意事项 - 确保目标页面的路径正确无误。 - 如果使用前端路由,请提前配置好路由规则。 - 在 SPA 中,避免直接使用 `window.location.href`,因为这会导致页面刷新,破坏单页应用的优势[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值