Android仿京東App購物車 二級列表+全選反選+Ok封裝+攔截器+結算+商品數量計算(完整程式碼)

zpf_發表於2017-12-19

複製即用,閱讀即懂

需要注入依賴和網路許可權ImageLoader的App

//Ok請求

    compile 'com.squareup.okhttp3:okhttp:3.9.1'

//Gson解析
    compile 'com.google.code.gson:gson:2.2.4'

//EventBus傳遞
    compile 'org.greenrobot:eventbus:3.1.1'

//ImageLoader
    compile files('libs/universal-image-loader-1.9.5.jar')

 

 

主佈局頭部佈局加二級列表(activity_main)

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">


    <ExpandableListView
        android:id="@+id/ex"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ExpandableListView>

    <!--底部檢視-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:background="#F00">

        <CheckBox
            android:id="@+id/selectAll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@id/selectAll"
            android:text="全選"
            android:textColor="#000"
            android:textSize="18sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="80dp"
            android:layout_toRightOf="@id/selectAll"
            android:text="總價:"
            android:textColor="#000"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="130dp"
            android:layout_toRightOf="@id/selectAll"
            android:text="0.0"
            android:textColor="#000"
            android:textSize="18sp" />


        <RelativeLayout
            android:layout_width="120dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:background="#FF0">


            <TextView
                android:id="@+id/count"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="個數"
                android:textColor="#000"
                android:textSize="18sp" />

        </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>

 

商家店鋪名稱,一級標題佈局(layout_group)

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

    <TextView
        android:id="@+id/storeName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:layout_toRightOf="@id/checkGroup"
        android:text="淘寶店鋪名稱"
        android:textColor="#000"
        android:textSize="20dp" />

</RelativeLayout>

商品列表,二級標題佈局(layout_child)

 

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">


    <CheckBox
        android:id="@+id/checkChild"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:scaleX="0.6"
        android:scaleY="0.6" />

    <ImageView
        android:id="@+id/img"
        android:layout_width="70dp"
        android:layout_height="80dp"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/checkChild"
        android:background="@mipmap/ic_launcher" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:layout_toRightOf="@id/img"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="酒紅色純紅色純羊毛西服套裝"
            android:textColor="@android:color/black"
            android:textSize="12sp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="24dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="¥390"
                android:textColor="@android:color/holo_red_dark"
                android:textSize="12sp"
                android:textStyle="bold" />

            <LinearLayout
                android:id="@+id/rl_edit"
                android:layout_width="120dp"
                android:layout_height="30dp"
                android:layout_marginLeft="50dp"
                android:background="@android:color/holo_orange_light">

                <TextView
                    android:id="@+id/lessen"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_margin="1dp"
                    android:layout_weight="1"
                    android:background="@android:color/white"
                    android:gravity="center"
                    android:text=" - "
                    android:textColor="@android:color/black" />

                <TextView
                    android:id="@+id/count"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_margin="1dp"
                    android:layout_weight="1"
                    android:background="@android:color/white"
                    android:gravity="center"
                    android:text="1" />

                <TextView
                    android:id="@+id/add"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_margin="1dp"
                    android:layout_weight="1"
                    android:background="@android:color/white"
                    android:gravity="center"
                    android:text=" + " />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

    <Button
        android:id="@+id/btnDelete"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_margin="5dp"
        android:background="@android:color/holo_blue_light"
        android:gravity="center"
        android:text="x"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="20sp"
        android:visibility="visible" />

</RelativeLayout>

 

自定義攔截器(Intercept)


import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * author:Created by ZhangPengFei on 2017/12/19.
 */

public class Intercept implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        HttpUrl url=original.url().newBuilder()
                .addQueryParameter("source","android")
                .build();
        //新增請求頭
        Request request = original.newBuilder()
                .url(url)
                .build();
        return chain.proceed(request);
    }
}

Ok封裝的工具請求類(OKHttpUtils)

/**
 * author:Created by ZhangPengFei on 2017/12/19.
 */


import android.os.Handler;
import android.util.Log;

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

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * author:Created by WangZhiQiang on 2017/12/5.
 */


public class OKHttpUtils {
    private static OKHttpUtils okHttpUtils;
    private static Handler handler = new Handler();


    //私有化構造方法
    public OKHttpUtils() {


    }


    /**
     * 獲取OKhttpClient例項化
     */
    public static OKHttpUtils getInstance() {
        if (null == okHttpUtils) {
            synchronized (OKHttpUtils.class) {
                if (null == okHttpUtils) {
                    okHttpUtils = new OKHttpUtils();
                }
            }
        }
        return okHttpUtils;
    }


    /**
     * 封裝的非同步Get請求
     */
    public void doGet(String path, Map<String, String> map, final IOkHttpUtils okHttpCallBack) {
        //建立一個字串容器
        StringBuilder sb = null;
        if (map.size() == 0) {
            if (null == sb) {
                sb = new StringBuilder();
                sb.append(path);
            }
        } else {
            for (String key : map.keySet()) {
                if (null == sb) {
                    sb = new StringBuilder();
                    sb.append(path);
                    sb.append("?");
                } else {
                    sb.append("&");
                }
                sb.append(key).append("=").append(map.get(key));
            }
        }


        //System.out.println("分類 : "+path + sb.toString());

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Intercept())//使用攔截器
                .build();
        Request request = new Request.Builder()
                .url(sb.toString())
                .get()
                .build();
        //OKHttp 網路
        Call call = okHttpClient.newCall(request);
        //非同步請求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //請求失敗
                Log.e("SKN", "OK請求失敗");
                okHttpCallBack.onFailed(e.getMessage());
            }


            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String str = response.body().string();
                //請求成功
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("WWWW", "請求成功" + str);
                        okHttpCallBack.onSuccess(str);
                    }
                });
            }
        });
    }
}

Ok封裝工具類的介面(IOkHttpUtils)


/**
 * author:Created by ZhangPengFei on 2017/12/19.
 */

/**
 * author:Created by Androidon 2017/12/10.
 */

public interface IOkHttpUtils {

    void onSuccess(String str);

    void onFailed(String message);

}

ImageLoader工具封裝類




import android.app.Application;

import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

/**
 * author:Created by ZhangPengFei on 2017/12/19.
 */


public class ImageApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(this)
                .memoryCacheExtraOptions(480, 800) // max width, max height,即儲存的每個快取檔案的最大長寬
                .threadPoolSize(5)//執行緒池內載入的數量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通過自己的記憶體快取實現
                .memoryCacheSize(2 * 1024 * 1024)
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .imageDownloader(new BaseImageDownloader(this, 5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超時時間
                .writeDebugLogs() // Remove for release app
                .build();//開始構建
        //初始化ImageLoader
        ImageLoader.getInstance().init(config);
    }
}

Json串的Bean類(JsonBean)


import java.util.List;

/**
 * author:Created by ZhangPengFei on 2017/12/19.
 */

public class JsonBean {

    /**
     * msg : 請求成功
     * code : 0
     * data : [{"list":[{"bargainPrice":22.9,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/2542855.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t1930/284/2865629620/390243/e3ade9c4/56f0a08fNbd3a1235.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2137/336/2802996626/155915/e5e90d7a/56f0a09cN33e01bd0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t1882/31/2772215910/389956/c8dbf370/56f0a0a2Na0c86ea6.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2620/166/2703833710/312660/531aa913/57709035N33857877.jpg!q70.jpg","num":1,"pid":24,"price":288,"pscid":2,"selected":0,"sellerid":1,"subhead":"三隻松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》","title":"三隻松鼠 堅果炒貨 零食奶油味 碧根果225g/袋"},{"bargainPrice":159,"createtime":"2017-10-14T21:49:15","detailUrl":"https://item.m.jd.com/product/5061723.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t8716/197/1271594444/173291/2f40bb4f/59b743bcN8509428e.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8347/264/1286771527/92188/5cf5ec04/59b7420fN65378e9e.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7363/165/3000956253/190883/179a372/59b743bfNd0c79d93.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7399/112/2935531768/183594/b77c7d4a/59b7441aNc3d40133.jpg!q70.jpg","num":7,"pid":90,"price":1233,"pscid":112,"selected":0,"sellerid":1,"subhead":"針織針織閃閃閃亮你的眼","title":"維邇旎 2017秋冬新款長袖針織連衣裙韓版氣質中長款名媛包臀A字裙 zx179709 黑色 XL"},{"bargainPrice":99,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/4345173.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6037/35/2944615848/95178/6cd6cff0/594a3a10Na4ec7f39.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6607/258/1025744923/75738/da120a2d/594a3a12Ne3e6bc56.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6370/292/1057025420/64655/f87644e3/594a3a12N5b900606.jpg!q70.jpg","num":1,"pid":45,"price":2999,"pscid":39,"selected":0,"sellerid":1,"subhead":"高清雙攝,就是清晰!2000+1600萬高清攝像頭,6GB大記憶體+高通驍龍835處理器,效能怪獸!","title":"一加手機5 (A5000) 6GB+64GB 月岩灰 全網通 雙卡雙待 移動聯通電信4G手機"},{"bargainPrice":11800,"createtime":"2017-10-10T17:33:37","detailUrl":"https://item.m.jd.com/product/4338107.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6700/155/2098998076/156185/6cf95035/595dd5a5Nc3a7dab5.jpg!q70.jpg","num":1,"pid":57,"price":5199,"pscid":40,"selected":0,"sellerid":1,"subhead":"【i5 MX150 2G視訊記憶體】全高清窄邊框 8G記憶體 256固態硬碟 支援指紋識別 預裝WIN10系統","title":"小米(MI)Air 13.3英寸全金屬輕薄筆記本(i5-7200U 8G 256G PCle SSD MX150 2G獨顯 FHD 指紋識別 Win10)銀\r\n"}],"sellerName":"商家1","sellerid":"1"},{"list":[{"bargainPrice":159,"createtime":"2017-10-14T21:49:15","detailUrl":"https://item.m.jd.com/product/5061723.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t8716/197/1271594444/173291/2f40bb4f/59b743bcN8509428e.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8347/264/1286771527/92188/5cf5ec04/59b7420fN65378e9e.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7363/165/3000956253/190883/179a372/59b743bfNd0c79d93.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7399/112/2935531768/183594/b77c7d4a/59b7441aNc3d40133.jpg!q70.jpg","num":1,"pid":91,"price":1344,"pscid":112,"selected":0,"sellerid":2,"subhead":"針織針織閃閃閃亮你的眼","title":"維邇旎 2017秋冬新款長袖針織連衣裙韓版氣質中長款名媛包臀A字裙 zx179709 黑色 XL"},{"bargainPrice":11800,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/5025518.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t8830/106/1760940277/195595/5cf9412f/59bf2ef5N5ab7dc16.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5428/70/1520969931/274676/b644dd0d/591128e7Nd2f70da0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5566/365/1519564203/36911/620c750c/591128eaN54ac3363.jpg!q70.jpg","num":1,"pid":58,"price":6399,"pscid":40,"selected":0,"sellerid":2,"subhead":"升級4G大視訊記憶體!Nvme協議Pcie SSD,速度快人一步】GTX1050Ti就選拯救者!專業遊戲鍵盤&新模具全新設計!","title":"聯想(Lenovo)拯救者R720 15.6英寸遊戲膝上型電腦(i5-7300HQ 8G 1T+128G SSD GTX1050Ti 4G IPS 黑)"}],"sellerName":"商家2","sellerid":"2"}]
     */

    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 {

        public boolean isChecked() {
            return checked;
        }

        public void setChecked(boolean checked) {
            this.checked = checked;
        }
        /**
         * list : [{"bargainPrice":22.9,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/2542855.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t1930/284/2865629620/390243/e3ade9c4/56f0a08fNbd3a1235.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2137/336/2802996626/155915/e5e90d7a/56f0a09cN33e01bd0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t1882/31/2772215910/389956/c8dbf370/56f0a0a2Na0c86ea6.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2620/166/2703833710/312660/531aa913/57709035N33857877.jpg!q70.jpg","num":1,"pid":24,"price":288,"pscid":2,"selected":0,"sellerid":1,"subhead":"三隻松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》","title":"三隻松鼠 堅果炒貨 零食奶油味 碧根果225g/袋"},{"bargainPrice":159,"createtime":"2017-10-14T21:49:15","detailUrl":"https://item.m.jd.com/product/5061723.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t8716/197/1271594444/173291/2f40bb4f/59b743bcN8509428e.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8347/264/1286771527/92188/5cf5ec04/59b7420fN65378e9e.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7363/165/3000956253/190883/179a372/59b743bfNd0c79d93.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7399/112/2935531768/183594/b77c7d4a/59b7441aNc3d40133.jpg!q70.jpg","num":7,"pid":90,"price":1233,"pscid":112,"selected":0,"sellerid":1,"subhead":"針織針織閃閃閃亮你的眼","title":"維邇旎 2017秋冬新款長袖針織連衣裙韓版氣質中長款名媛包臀A字裙 zx179709 黑色 XL"},{"bargainPrice":99,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/4345173.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6037/35/2944615848/95178/6cd6cff0/594a3a10Na4ec7f39.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6607/258/1025744923/75738/da120a2d/594a3a12Ne3e6bc56.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6370/292/1057025420/64655/f87644e3/594a3a12N5b900606.jpg!q70.jpg","num":1,"pid":45,"price":2999,"pscid":39,"selected":0,"sellerid":1,"subhead":"高清雙攝,就是清晰!2000+1600萬高清攝像頭,6GB大記憶體+高通驍龍835處理器,效能怪獸!","title":"一加手機5 (A5000) 6GB+64GB 月岩灰 全網通 雙卡雙待 移動聯通電信4G手機"},{"bargainPrice":11800,"createtime":"2017-10-10T17:33:37","detailUrl":"https://item.m.jd.com/product/4338107.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6700/155/2098998076/156185/6cf95035/595dd5a5Nc3a7dab5.jpg!q70.jpg","num":1,"pid":57,"price":5199,"pscid":40,"selected":0,"sellerid":1,"subhead":"【i5 MX150 2G視訊記憶體】全高清窄邊框 8G記憶體 256固態硬碟 支援指紋識別 預裝WIN10系統","title":"小米(MI)Air 13.3英寸全金屬輕薄筆記本(i5-7200U 8G 256G PCle SSD MX150 2G獨顯 FHD 指紋識別 Win10)銀\r\n"}]
         * sellerName : 商家1
         * sellerid : 1
         */


        private boolean checked;
        private String sellerName;
        private String sellerid;
        private List<ListBean> list;

        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 {

            public boolean isChecked() {
                return checked;
            }

            public void setChecked(boolean checked) {
                this.checked = checked;
            }
            /**
             * bargainPrice : 22.9
             * createtime : 2017-10-14T21:48:08
             * detailUrl : https://item.m.jd.com/product/2542855.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends
             * images : https://m.360buyimg.com/n0/jfs/t1930/284/2865629620/390243/e3ade9c4/56f0a08fNbd3a1235.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2137/336/2802996626/155915/e5e90d7a/56f0a09cN33e01bd0.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t1882/31/2772215910/389956/c8dbf370/56f0a0a2Na0c86ea6.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t2620/166/2703833710/312660/531aa913/57709035N33857877.jpg!q70.jpg
             * num : 1
             * pid : 24
             * price : 288.0
             * pscid : 2
             * selected : 0
             * sellerid : 1
             * subhead : 三隻松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》
             * title : 三隻松鼠 堅果炒貨 零食奶油味 碧根果225g/袋
             */


            private boolean checked;
            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 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;
            }
        }
    }
}

 

主佈局(MainActivity)




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 org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements IShopCarPresenter {

    private ExpandableListView ex;
    private CheckBox selectAll;
    private TextView price;
    private TextView count;
    private ShopCarPresenter shopCarPresenter;
    private int uid = 3384;
    private List<JsonBean.DataBean> groupList = new ArrayList<>();
    private List<List<JsonBean.DataBean.ListBean>> childList = new ArrayList<>();
    private MyExAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();//初始化檢視
        /**
         * 用於傳控制元件,
         * 需要匯入依賴才可以進行傳送
         */
        EventBus.getDefault().register(this);        //全選/全不選
        selectAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //設定全選
                myAdapter.changeAllListCbState(selectAll.isChecked());
            }
        });
    }

    //每次進這個頁面都要甩你
    @Override
    protected void onResume() {
        super.onResume();
        initData();//初始化資料
    }

    //初始化資料
    private void initData() {
        //例項化P層
        shopCarPresenter = new ShopCarPresenter(this);
        shopCarPresenter.receive(uid + "");
    }

    //初始化集合
    private void initView() {
        ex = (ExpandableListView) findViewById(R.id.ex);//二級列表
        selectAll = (CheckBox) findViewById(R.id.selectAll);//全選按鈕
        price = (TextView) findViewById(R.id.price);//價格
        count = (TextView) findViewById(R.id.count);//數量
    }

    @Override
    public void onSuccess(List<JsonBean.DataBean> data) {
        //清空一下多餘的列表展示
        groupList.clear();
        childList.clear();
        //將商家的資料加入到大集合grouList
        groupList.addAll(data);
        //將商家下商品的資料全部新增到小集合childList
        for (int i = 0; i < data.size(); i++) {
            List<JsonBean.DataBean.ListBean> list = data.get(i).getList();
            childList.add(list);
        }
        /**
         * 配置介面卡
         * 將商家的大集合和商家下的商品小集合全部傳到介面卡
         */
        myAdapter = new MyExAdapter(MainActivity.this, groupList, childList);
        ex.setAdapter(myAdapter);
        //二級列表預設展開
        for (int i = 0; i < data.size(); i++) {
            ex.expandGroup(i);//二級列表自帶的方法
        }
        //重新整理一下介面卡
        myAdapter.notifyDataSetChanged();
    }

    @Override
    public void onFailed() {

    }
    @Subscribe
    public void onMessageEvent(MessageEvent event) {
        selectAll.setChecked(event.isCheckd());
    }

    //計算總價和總數量
    @Subscribe
    public void onMessageEven(PriceAndCountEvent event) {
        price.setText(event.getPrice() + ".00");
        count.setText("(" + event.getCount() + ")");
    }
}

P層(ShopCarPresenter)

 

 


import java.util.List;

/**
 * author:Created by ZhangPengFei on 2017/12/19.
 */

public class ShopCarPresenter implements IShopCarModel {

    private ShopCarModel shopCarModel;
    private IShopCarPresenter iShopCarPresenter;

    public ShopCarPresenter(IShopCarPresenter iShopCarPresenter) {
        this.iShopCarPresenter = iShopCarPresenter;
        shopCarModel = new ShopCarModel();
    }

    public void receive(String uid) {
        shopCarModel.receive(uid,this);
    }

    @Override
    public void onSuccess(List<JsonBean.DataBean> data) {
        iShopCarPresenter.onSuccess(data);
    }

    @Override
    public void onFailed() {
        iShopCarPresenter.onFailed();
    }
}

M層(ShopCarModel)

 

 


import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;

/**
 * author:Created by ZhangPengFei on 2017/12/19.
 */

public class ShopCarModel {

    public void receive(String uid, final IShopCarModel iShopCarModel) {
        OKHttpUtils instance = OKHttpUtils.getInstance();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("uid",uid);
        instance.doGet("http://120.27.23.105/product/getCarts", hashMap, new IOkHttpUtils() {
            @Override
            public void onSuccess(String str) {
                if(str!=null){
                    Gson gson = new Gson();
                    JsonBean jsonBean = gson.fromJson(str, JsonBean.class);
                    if(jsonBean!=null){
                        List<JsonBean.DataBean> data = jsonBean.getData();
                        iShopCarModel.onSuccess(data);
                    }
                }
            }

            @Override
            public void onFailed(String message) {
                iShopCarModel.onFailed();
            }
        });
    }

}

M層傳值的介面(IShopCarModel)

 



import java.util.List;

/**
 * author:Created by ZhangPengFei on 2017/12/19.
 */

public interface IShopCarModel {

    void onSuccess(List<JsonBean.DataBean> data);

    void onFailed();

}

P層傳值的介面(IShopCarPresenter)

 



import java.util.List;

/**
 * author:Created by ZhangPengFei on 2017/12/19.
 */

public interface IShopCarPresenter {

    void onSuccess(List<JsonBean.DataBean> data);

    void onFailed();

}

Event用於在介面卡和Activity之間傳送接收控制元件的介面卡(MessageEvent)

 

 


/**
 * Created by HASEE on 2017/11/22.
 */

public class MessageEvent {
    private boolean checkd;
    public boolean isCheckd(){
        return checkd;
    }
    public void  setCheckd(boolean checkd){
        this.checkd=checkd;
    }
}

計算選中數量和價格的介面卡(PriceAndCountEvent)

 



/**
 * Created by HASEE on 2017/11/22.
 */

public class PriceAndCountEvent {
    private int price;
    private int count;
    private int to;

    public int getPrice() {
        return price;
    }

    public int getCount() {
        return count;
    }

    public int getTo(){
        return  to;
    }

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

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

    public void setTo(int to) {
        this.to = to;
    }
}

ExpandAbleListView二級列表的介面卡(MyExAdapter)

 



import android.content.Context;
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.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * author:Created by ZhangPengFei on 2017/12/19.
 */

public class MyExAdapter extends BaseExpandableListAdapter {

    private Context context;
    private List<JsonBean.DataBean> groupList;
    private List<List<JsonBean.DataBean.ListBean>> childList;

    public MyExAdapter(Context context, List<JsonBean.DataBean> groupList, List<List<JsonBean.DataBean.ListBean>> childList) {
        this.context = context;
        this.groupList = groupList;
        this.childList = childList;
    }

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

    @Override
    public int getChildrenCount(int i) {
        return childList.get(i).size();
    }

    @Override
    public Object getGroup(int i) {
        return groupList.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        return childList.get(i).get(i1);
    }

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

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

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

    /**
     * 裝載一級列表資料
     * 商家的全選框
     * 商家名稱
     */
    class ViewHolder {
        CheckBox checkGroup;
        TextView storeName;
    }

    @Override
    public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = View.inflate(context, R.layout.layout_group, null);
            holder.checkGroup = view.findViewById(R.id.checkGroup);
            holder.storeName = view.findViewById(R.id.storeName);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        holder.storeName.setText(groupList.get(i).getSellerName());
        //設定以及列表的點選狀態
        holder.checkGroup.setChecked(groupList.get(i).isChecked());
        //一級列表checkBox的點選事件
        holder.checkGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //判斷一級列表核取方塊的狀態,設定為true或false
                groupList.get(i).setChecked(holder.checkGroup.isChecked());
                //改變二級checkBox的狀態
                changeChildState(i, holder.checkGroup.isChecked());
                //算錢
                EventBus.getDefault().post(computer());
                //改變全選狀態   isAllGroupCbSelect判斷一級是否全部選中
                changeAllState(isAllGroupSelect());
                //必重新整理
                notifyDataSetChanged();
            }
        });
        return view;
    }

    /**
     * 裝載資料
     * 裝載當前店鋪下的
     * 要展示的商品
     */
    class ViewHolder1 {
        CheckBox checkChild;
        ImageView img;
        TextView title;
        TextView price;
        TextView lessen;
        TextView count;
        TextView add;
        Button btnDelete;
    }

    @Override
    public View getChildView(final int i, int i1, boolean b, View view, ViewGroup viewGroup) {
        final JsonBean.DataBean.ListBean bean = childList.get(i).get(i1);
        final ViewHolder1 holder1;
        /**
         * 優化,判斷為空
         */
        if (view == null) {
            holder1 = new ViewHolder1();
            //獲取檢視
            view = View.inflate(context, R.layout.layout_child, null);
            /**
             * 獲取ID
             */
            holder1.checkChild = view.findViewById(R.id.checkChild);//選框
            holder1.img = view.findViewById(R.id.img);//圖片
            holder1.title = view.findViewById(R.id.title);//標題
            holder1.price = view.findViewById(R.id.price);//價格
            holder1.lessen = view.findViewById(R.id.lessen);//減
            holder1.count = view.findViewById(R.id.count);//數量
            holder1.add = view.findViewById(R.id.add);//加
            holder1.btnDelete = view.findViewById(R.id.btnDelete);//刪除的按鈕
            view.setTag(holder1);
        } else {
            holder1 = (ViewHolder1) view.getTag();
        }
        ImageLoader.getInstance().displayImage(bean.getImages(), holder1.img);
        holder1.title.setText(bean.getTitle());
        holder1.price.setText(bean.getPrice() + "");
        holder1.count.setText(bean.getNum() + "");
        //設定二級列表checkbox的屬性
        holder1.checkChild.setChecked(childList.get(i).get(i1).isChecked());
        //二級列表的點選事件
        holder1.checkChild.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //設定該條目中的checkbox屬性值
                bean.setChecked(holder1.checkChild.isChecked());
                //計算價錢
                PriceAndCountEvent priceAndCountEvent = computer();
                EventBus.getDefault().post(priceAndCountEvent);
                //判斷當前checkbox是選中的狀態
                if (holder1.checkChild.isChecked()) {
                    //如果全部選中(isAllChildCbSelected)
                    if (isAllChildCbSelected(i)) {
                        //改變一級列表的狀態
                        changeGroupState(i, true);
                        //改變全選的狀態
                        changeAllState(isAllGroupSelect());
                    }
                } else {
                    //如果沒有全部選中,一級列表的checkbox為false不為選中
                    changeGroupState(i, false);
                    changeAllState(isAllGroupSelect());
                }
                notifyDataSetChanged();
            }
        });//加號
        holder1.add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int num = bean.getNum();
                //num為int型別所以要加空字串
                holder1.count.setText(++num + "");
                bean.setNum(num);
                //如果二級列表的checkbox為選中,計算價錢
                if (holder1.checkChild.isChecked()) {
                    PriceAndCountEvent priceAndCountEvent = computer();
                    EventBus.getDefault().post(priceAndCountEvent);
                }
            }
        });
        //減號
        holder1.lessen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int num = bean.getNum();
                if (num == 1) {
                    return;
                }
                holder1.count.setText(--num + "");
                bean.setNum(num);
                if (holder1.checkChild.isChecked()) {
                    PriceAndCountEvent priceAndCountEvent = computer();
                    EventBus.getDefault().post(priceAndCountEvent);
                }
            }
        });
        return view;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return false;
    }

    //改變二級列表的checkBox的狀態,如果一級選中,控制二級也選中
    private void changeChildState(int i, boolean flag) {
        List<JsonBean.DataBean.ListBean> listBeen = childList.get(i);
        for (int j = 0; j < listBeen.size(); j++) {
            JsonBean.DataBean.ListBean listBean = listBeen.get(j);
            listBean.setChecked(flag);
        }
    }

    //判斷一級列表是否全部選中
    public boolean isAllGroupSelect() {
        for (int i = 0; i < childList.size(); i++) {
            JsonBean.DataBean dataBean = groupList.get(i);
            if (!dataBean.isChecked()) {
                return false;
            }
        }
        return true;
    }

    //改變全選的狀態
    private void changeAllState(boolean flag) {
        //匯入的類
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setCheckd(flag);
        EventBus.getDefault().post(messageEvent);
    }

    //改變列表的checkBox的狀態
    private void changeGroupState(int i,boolean flag){
        JsonBean.DataBean dataBean = groupList.get(i);
        dataBean.setChecked(flag);
    }


    //判斷二級列表是否全部選中
    private boolean isAllChildCbSelected(int i) {
        List<JsonBean.DataBean.ListBean> listBeen = childList.get(i);
        for (int j = 0; j < listBeen.size(); j++) {
            JsonBean.DataBean.ListBean listBean = listBeen.get(j);
            if (!listBean.isChecked()) {
                return false;
            }
        }
        return true;
    }

    //設定全選,反選
    public void changeAllListCbState(boolean flag) {
        for (int i = 0; i < childList.size(); i++) {
            changeGroupState(i, flag);
            changeChildState(i, flag);
        }
        //算錢
        EventBus.getDefault().post(computer());
        notifyDataSetChanged();
    }

    //計算列表的價錢
    private PriceAndCountEvent computer() {
        int count = 0;
        int price = 0;
        int to = 0;
        for (int i = 0; i < childList.size(); i++) {
            List<JsonBean.DataBean.ListBean> listBeen = childList.get(i);
            for (int j = 0; j < listBeen.size(); j++) {
                JsonBean.DataBean.ListBean listBean = listBeen.get(j);
                if (listBean.isChecked()) {
                    price += listBean.getNum() * listBean.getPrice();
                    count += listBean.getNum();
                    to += listBean.getNum();
                }
            }
        }
        PriceAndCountEvent priceAndCountEvent = new PriceAndCountEvent();
        priceAndCountEvent.setCount(count);
        priceAndCountEvent.setPrice(price);
        priceAndCountEvent.setTo(to);
        return priceAndCountEvent;
    }

}

如果JsonBean類裡面沒有isCheck的有參需要手動新增

 

 

//放入DateBean

        private boolean checked;
public boolean isChecked() {
            return checked;
        }

        public void setChecked(boolean checked) {
            this.checked = checked;
        }
		
//放入ListBean

            private boolean checked;
public boolean isChecked() {
                return checked;
            }

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

相關文章