1. 程式人生 > >購物車(二級列表)

購物車(二級列表)

購物車 (二級列表)

效果:
在這裡插入圖片描述

一、先寫許可權

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

二、導依賴

Eventbus依賴:

compile 'org.greenrobot:eventbus:3.1.1'

gson依賴:

implementation 'com.google.code.gson:gson:2.8.5'

OkHttp依賴:

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

recyclerView依賴:

implementation 'com.android.support:recyclerview-v7:28.0.0'

glid依賴:

repositories {
  mavenCentral()
  maven { url 'https://maven.google.com' }
}
 
dependencies {
  compile 'com.github.bumptech.glide:glide:4.3.1'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
}

接下來就是佈局和具體的程式碼了

一、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=".MainActivity">

    <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="50dp"
        android:layout_alignParentBottom="true"
        android:background="@android:color/white"
        android:gravity="center_vertical">

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@+id/checkbox2"
            android:gravity="center_vertical"
            android:text="全選"
            android:textSize="20sp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100dp"
            android:orientation="horizontal">

            <TextView

                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="合計 :" />


            <TextView
                android:id="@+id/tv_price"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_marginLeft="10dp"
                android:paddingRight="10dp"
                android:text="0"
                android:textColor="@android:color/holo_red_light" />


            <TextView
                android:layout_marginLeft="150dp"
                android:id="@+id/tv_num"
                android:layout_width="150dp"
                android:layout_height="50dp"
                android:background="@android:color/holo_red_dark"
                android:gravity="center"
                android:padding="10dp"
                android:text="結算(0)"
                android:textColor="@android:color/white" />
        </LinearLayout>
    </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="10dp"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/cb_parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:focusable="false" />

    <TextView
        android:id="@+id/tv_sign"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="標記" />

    <TextView
        android:id="@+id/tv_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="12345678" />

</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="match_parent"

    android:gravity="center_vertical"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/cb_child"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp"
        android:focusable="false" />

    <RelativeLayout
        android:layout_width="100dp"
        android:layout_height="100dp">

        <TextView
            android:id="@+id/tv_sbt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:text="三隻松鼠大禮包發動機" />

        <ImageView
            android:id="@+id/img"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_below="@id/tv_sbt"
            android:src="@mipmap/ic_launcher" />
    </RelativeLayout>


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

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

            android:text="¥3000.00" />

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="什麼" />

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

            <com.gj.buycarej.core.MyView
                android:id="@+id/mv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"></com.gj.buycarej.core.MyView>

        </LinearLayout>

    </LinearLayout>

    <Button
        android:id="@+id/tv_del"
        android:layout_width="20dp"
        android:layout_height="20dp" />
</LinearLayout>

四、加減框自定義view的佈局

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <Button
        android:id="@+id/btn_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="+"/>
    <EditText
        android:id="@+id/et_et"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:text="1"
        android:textSize="20sp"/>
    <Button
        android:id="@+id/btn_del"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="-"/>
</LinearLayout>

五、Main的程式碼(用到的佈局檔案是Main佈局)

package com.gj.buycarej;

import android.app.Activity;
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.gj.buycarej.adapter.StarExpanderAdapter;
import com.gj.buycarej.bean.GsonBean;
import com.gj.buycarej.bean.MessageEvent;
import com.gj.buycarej.bean.PriceAndCountEvent;
import com.gj.buycarej.core.IView;
import com.gj.buycarej.presenter.PresentCar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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


public class MainActivity extends AppCompatActivity implements IView {


    private ExpandableListView elv;
    ArrayList<GsonBean.DataBean> dataBeen = new ArrayList<>();
    private CheckBox checkquan;
    private List<GsonBean.DataBean.ListBean> lists;
    ArrayList<List<GsonBean.DataBean.ListBean>> listBean = new ArrayList<>();
    private StarExpanderAdapter adapter;
    private TextView tv_price;
    private TextView tv_num;
    private PresentCar presentCar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //註冊一下
        EventBus.getDefault().register(this);
        //獲取控制元件
        elv = (ExpandableListView) findViewById(R.id.elv);
        checkquan = (CheckBox) findViewById(R.id.checkbox2);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_num = (TextView) findViewById(R.id.tv_num);
        //獲取資料
        presentCar = new PresentCar();
        presentCar.attachView(this);
        presentCar.getNews();
        checkquan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //設定全選
                adapter.changeAllListCbState(checkquan.isChecked());
            }
        });

    }
    //銷燬方法
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //eventBus銷燬
        EventBus.getDefault().unregister(this);
        if (presentCar!=null){
            presentCar.detachView();
        }

    }
    @Override
    public void Success(String tag, List<GsonBean.DataBean> list) {
        dataBeen.addAll(list);
        for (int i = 0; i < dataBeen.size(); i++) {
            GsonBean.DataBean bean = dataBeen.get(i);
            lists = bean.getList();
            listBean.add(lists);
        }
        adapter = new StarExpanderAdapter(MainActivity.this,dataBeen,listBean);
        elv.setAdapter(adapter);
        //隱藏二級列表前小三角
        elv.setGroupIndicator(null);
        //使二級列表一直展示
        for (int i = 0; i <dataBeen.size() ; i++) {
            elv.expandGroup(i);
        }
    }
    @Override
    public void Failed(String tag, Exception e) {
    }
    //必寫註解
    @Subscribe
    public void onMessageEvent(MessageEvent event) {
        checkquan.setChecked(event.isChecked());
    }
    @Subscribe
    public void onMessageEvent(PriceAndCountEvent event) {
        tv_num.setText("結算(" + event.getCount() + ")");
        tv_price.setText(event.getPrice() + "");
    }
}

六、P層請求資料

package com.gj.buycarej.presenter;

import com.gj.buycarej.bean.GsonBean;
import com.gj.buycarej.core.Callback;
import com.gj.buycarej.core.IView;
import com.gj.buycarej.http.HttpUtils;

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

public class PresentCar {
    private IView inv;
 
    public void attachView(IView inv) {
        this.inv = inv;
    }
    public void getNews() {
        //type=top&key=dbedecbcd1899c9785b95cc2d17131c5
        Map<String, String> map = new HashMap<>();
 
        HttpUtils.getInstanse().get("http://120.27.23.105/product/getCarts?uid=100", map, new Callback() {
            @Override
            public void onSuccess(String tag, Object o) {
                GsonBean bean = (GsonBean) o;
                if (bean != null) {
                    List<GsonBean.DataBean> data = bean.getData();
 
                    inv.Success(tag, data);
                }
            }
 
            @Override
            public void onFailure(String tag, Exception e) {
                inv.Failed(tag, e);
            }
 
 
        }, GsonBean.class, "news");
    }
    public void detachView() {
        if (inv != null) {
            inv = null;
        }
    }
}

七、用到的介面及自定義view

介面一、

package com.gj.buycarej.core;

public interface Callback {
    void onSuccess(String tag,Object o);
    void onFailure(String tag,Exception e);
}

介面二、

package com.gj.buycarej.core;

import com.gj.buycarej.bean.GsonBean;

import java.util.List;

public interface IView {
    void Success (String tag, List<GsonBean.DataBean> list);
    void Failed(String tag,Exception e);
}

自定義view(此處用到的佈局是加減的佈局檔案)

package com.gj.buycarej.core;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.gj.buycarej.R;

public class MyView extends LinearLayout {
    private OnAddDelClickLstener lister;
    private Button btn_add;
    private Button txtAdd;
    private EditText et_et;
    private Button btn_del;
 
    //定義一個對外開放的介面
    public interface OnAddDelClickLstener{
        void onAddClick(View v);
        void onDelClick(View v);
    }
    public void setOnAddDelClickLstener(OnAddDelClickLstener lister){
        if(lister!=null){
            this.lister = lister;
        }
    }
    public MyView(Context context) {
        this(context,null);
    }
 
    public MyView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }
 
    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs, defStyleAttr);
    }
 
    private void initView(Context context, AttributeSet attrs, int defStyleAttr) {
        View.inflate(context, R.layout.item_jj,this);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_del = (Button) findViewById(R.id.btn_del);
        et_et = (EditText) findViewById(R.id.et_et);
 
        btn_del.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("AddDeleteView","點選了減號");
                lister.onDelClick(view);
            }
        });
        btn_add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("txtAdd","點選了加號");
                lister.onAddClick(view);
            }
        });
 
    } 
}

八、

package com.gj.buycarej.http;

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


import com.gj.buycarej.core.Callback;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Map;
 
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
 
 
public class HttpUtils {
    private static final String TAG = "HttpUtils";
    private static volatile HttpUtils instanse;
    final static Handler handler = new Handler();
 
    private HttpUtils() {
 
    }
    public static HttpUtils getInstanse() {
        if (null == instanse) {
            synchronized (HttpUtils.class) {
                if (instanse == null) {
                    instanse = new HttpUtils();
                }
            }
        }
        return instanse;
    }
    public void get(String url, Map<String, String> map, final Callback callBack,
                    final Class cls, final String tag) {
        // http://www.baoidu.com/login?mobile=11111&password=11111&age=1&name=zw
 
        // 1.http://www.baoidu.com/login                --------? key=value&key=value
        // 2.http://www.baoidu.com/login?               --------- key=value&key=value
        // 3.http://www.baoidu.com/login?mobile=11111   -----&key=value&key=value
        final StringBuffer sb = new StringBuffer();
        sb.append(url);
 
        if (TextUtils.isEmpty(url)) {
            return;
        }
        // 如果包含?說明是2.3型別
        if (url.contains("?")) {
            // 如果包含?並且?是最後一位,對應是2型別
            if (url.indexOf("?") == url.length() - 1) {
 
            } else {
                // 如果包含?並且?不是最後一位,對應是3型別
                sb.append("&");
            }
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }
        if (sb.indexOf("&") != -1) {
            sb.deleteCharAt((sb.lastIndexOf("&")));
        }
        Log.i(TAG, "get:url " + sb.toString());
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder()
                .get()
                .url(sb.toString())
                .build();
        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(tag,e);
                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String s = response.body().string();
                handler.post(new Runnable() {
                    Object o;
                    @Override
                    public void run() {
                        if(TextUtils.isEmpty(s)){
                            o=null;
                        }else
                        {
                            o = new Gson().fromJson(s, cls);
                        }
                        callBack.onSuccess(tag,o);
                    }
                });
            }
        });
    }
}

九、介面卡層(此處用到了一級佈局和二級佈局)

package com.gj.buycarej.adapter;

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

import com.bumptech.glide.Glide;
import com.gj.buycarej.R;
import com.gj.buycarej.bean.GsonBean;
import com.gj.buycarej.bean.MessageEvent;
import com.gj.buycarej.bean.PriceAndCountEvent;
import com.gj.buycarej.core.MyView;

import org.greenrobot.eventbus.EventBus;

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

public class StarExpanderAdapter extends BaseExpandableListAdapter {
    Context context;
    List<GsonBean.DataBean> dataBeen;
    ArrayList<List<GsonBean.DataBean.ListBean>> listBean;
 
 
 
    public StarExpanderAdapter(Context context, List<GsonBean.DataBean> dataBeen, ArrayList<List<GsonBean.DataBean.ListBean>> listBean) {
        this.context = context;
        this.dataBeen = dataBeen;
        this.listBean = listBean;
 
    }
 
    @Override
    public int getGroupCount() {
        return dataBeen.size();
    }
 
    @Override
    public int getChildrenCount(int i) {
        return listBean.get(i).size();
    }
 
    @Override
    public Object getGroup(int i) {
            return dataBeen.get(i);
    }
 
    @Override
    public Object getChild(int i, int i1) {
        return listBean.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;
    }
    //一級列表佈局
    @Override
    public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
        final GsonBean.DataBean groupBean = dataBeen.get(i);
        final GroupViewHolder holder;
        if(view==null){
            holder = new GroupViewHolder();
            view = View.inflate(context, R.layout.item_yj, null);
            holder.tv_sbt = view.findViewById(R.id.tv_sign);
            holder.cbgroup = view.findViewById(R.id.cb_parent);
            view.setTag(holder);
        }else
        {
            holder = (GroupViewHolder) view.getTag();
        }
        holder.cbgroup.setChecked(groupBean.isGropuCb());
        holder.tv_sbt.setText(groupBean.getSellerName());
        //一級列表checkBox的點選事件
        holder.cbgroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //判斷一級列表複選框的狀態  設定為true或false
                groupBean.setGropuCb(holder.cbgroup.isChecked());
                //改變二級checkbod的狀態
                changeChildeCbState(i,holder.cbgroup.isChecked());
                //算錢
                EventBus.getDefault().post(compute());
                //改變全選狀態   isAllGroupCbSelect判斷一級是否全部選中
                changeAllCbState(isAllGroupCbSelected());
                //必重新整理
                notifyDataSetChanged();
            }
        });
        return view;
    }
    //二級列表佈局
    @Override
    public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {
        final GsonBean.DataBean.ListBean clildBean = this.listBean.get(i).get(i1);
        final ChildViewHolder childViewHolder;
        if(view==null){
           view = View.inflate(context, R.layout.item_ej, null);
           childViewHolder = new ChildViewHolder();
            childViewHolder.tv_sbt = (TextView) view.findViewById(R.id.tv_sbt);
            childViewHolder.img = (ImageView) view.findViewById(R.id.img);
            childViewHolder.tv_pri = (TextView) view.findViewById(R.id.tv_pri);
            childViewHolder.tv_content = (TextView) view.findViewById(R.id.tv_content);
            childViewHolder.cbChild =view.findViewById(R.id.cb_child);
            childViewHolder.mv = view.findViewById(R.id.mv);
            childViewHolder.tv_del = view.findViewById(R.id.tv_del);
            childViewHolder.et_et = (EditText) childViewHolder.mv.findViewById(R.id.et_et);
            view.setTag(childViewHolder);
       }else{
            childViewHolder = (ChildViewHolder) view.getTag();
        }
        childViewHolder.tv_sbt.setText(clildBean.getTitle());
        String images = clildBean.getImages();
        String[] split = images.split("\\|");
        Glide.with(context).load(split[0]).into(childViewHolder.img);
        childViewHolder.tv_pri.setText(clildBean.getPrice()+"");
        childViewHolder.tv_content.setText(clildBean.getSubhead());
        childViewHolder.cbChild.setChecked(clildBean.isChildCb());
        childViewHolder.et_et.setText(clildBean.getNum()+"");
        //加號
        childViewHolder.mv.setOnAddDelClickLstener(new MyView.OnAddDelClickLstener() {
            @Override
            public void onAddClick(View v) {
                int num = clildBean.getNum();
                //num為int型別所以要加空字串
                childViewHolder.et_et.setText(++num+"");
                clildBean.setNum(num);
                //如果二級列表的checkbox為選中,計算價錢
                if (childViewHolder.cbChild.isChecked()){
                    PriceAndCountEvent priceAndCountEvent = (PriceAndCountEvent) compute();
                    EventBus.getDefault().post(priceAndCountEvent);
                }
            }
        //減號
            @Override
            public void onDelClick(View v) {
                int num = clildBean.getNum();
                if(num==1){
                    return;
                }
                childViewHolder.et_et.setText(--num+"");
                clildBean.setNum(num);
                if(childViewHolder.cbChild.isChecked()){
                    PriceAndCountEvent priceAndCountEvent = (PriceAndCountEvent) compute();
                    EventBus.getDefault().post(priceAndCountEvent);
                }
            }
        });
        //刪除
        childViewHolder.tv_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<GsonBean.DataBean.ListBean> listBeen = listBean.get(i);
                GsonBean.DataBean.ListBean remove = listBeen.remove(i1);
                if(listBeen.size()==0){
                    //先移除二級列表的集合,再移除一級列表的集合
                    listBean.remove(i);
                    dataBeen.remove(i);
                }
                //算錢
                EventBus.getDefault().post(compute());
                notifyDataSetChanged();
            }
        });
 
        //二級列表的點選事件
        childViewHolder.cbChild.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //設定該條目物件裡的checked屬性值
                clildBean.setChildCb(childViewHolder.cbChild.isChecked());
                //計算價錢
                PriceAndCountEvent priceAndCountEvent = (PriceAndCountEvent) compute();
                EventBus.getDefault().post(priceAndCountEvent);
                //判斷當前checkbox是選中的狀態
                if(childViewHolder.cbChild.isChecked()){
                    //如果全部選中(isAllChildCbSelected)
                    if(isAllChildCbSelected(i)){
                        //改變一級列表的狀態
                        changGroupCbState(i,true);
                        //改變全選的狀態
                        changeAllCbState(isAllGroupCbSelected());
                    }
                }else {
                    //如果沒有全部選中,一級列表的checkbox為false不為選中
                    changGroupCbState(i,false);
                    changeAllCbState(isAllGroupCbSelected());
                }
                notifyDataSetChanged();
            }
        });
 
        return view;
    }
 
    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }
    class GroupViewHolder {
        CheckBox cbgroup;
        TextView tv_sbt;
    }
    class ChildViewHolder {
        TextView tv_sbt;
        ImageView img;
        TextView tv_pri;
        TextView tv_content;
        CheckBox cbChild;
        MyView mv;
        TextView tv_del;
 
        EditText et_et;
    }
 
    /**
     * 改變二級列表checkbox狀態
     * 如果一級選中,控制二級也選中
     * @param i
     * @param flag
     */
     private void changeChildeCbState(int i,boolean flag){
         List<GsonBean.DataBean.ListBean> listBeen = listBean.get(i);
         for (int j = 0; j <listBeen.size(); j++) {
             GsonBean.DataBean.ListBean listBean = listBeen.get(j);
             listBean.setChildCb(flag);
         }
     }
    /**
     * 判斷一級列表是否全選中
     * @return
     */
     private boolean isAllGroupCbSelected(){
         for (int i = 0; i <dataBeen.size() ; i++) {
             GsonBean.DataBean dataBean = dataBeen.get(i);
             if(!dataBean.isGropuCb()){
                 return false;
             }
         }
         return true;
     }
    /**
     * 改變全選的狀態
     *
     * @param flag
     */
     private void changeAllCbState(boolean flag){
         MessageEvent messageEvent = new MessageEvent();
         messageEvent.setChecked(flag);
         EventBus.getDefault().post(messageEvent);
     }
    /**
     * 判斷二級列表是否全部選中
     * @param i
     * @return
     */
    private boolean isAllChildCbSelected (int i){
         List<GsonBean.DataBean.ListBean> listBeen = listBean.get(i);
         for (int j = 0; j <listBeen.size() ; j++) {
             GsonBean.DataBean.ListBean listBean = listBeen.get(j);
             if(!listBean.isChildCb()){
                 return false;
             }
         }
         return true;
     }
    /**
     * 改變一級列表checkbox狀態
     *
     * @param i
     */
     private void changGroupCbState(int i,boolean flag){
         GsonBean.DataBean dataBean = dataBeen.get(i);
         dataBean.setGropuCb(flag);
     }
    /**
     * 改變二級列表checkbox狀態
     * @param i
     * @param flag
     */
     private void changeChildCbState(int i,boolean flag){
         List<GsonBean.DataBean.ListBean> listBeen = listBean.get(i);
         for (int j = 0; j <listBeen.size() ; j++) {
             GsonBean.DataBean.ListBean listBean = listBeen.get(j);
             listBean.setChildCb(flag);
         }
     }
    /**
     * 計算列表中,選中的錢和數量
     */
     private Object compute(){
        int count = 0;
         int price = 0;
         for (int i = 0; i <listBean.size() ; i++) {
             List<GsonBean.DataBean.ListBean> listBeen = listBean.get(i);
             for (int j = 0; j <listBeen.size() ; j++) {
                 GsonBean.DataBean.ListBean listBean = listBeen.get(j);
                 if(listBean.isChildCb()){
                     price+=listBean.getNum()*listBean.getPrice();
                     count+=listBean.getNum();
                 }
             }
         }
         PriceAndCountEvent priceAndCountEvent = new PriceAndCountEvent();
         priceAndCountEvent.setCount(count);
         priceAndCountEvent.setPrice(price);
         return priceAndCountEvent;
     }
    /**
     * 設定全選、反選
     *
     * @param flag
     */
    public void changeAllListCbState(boolean flag) {
        for (int i = 0; i < dataBeen.size(); i++) {
            changGroupCbState(i, flag);
            changeChildCbState(i, flag);
        }
        //算錢
        EventBus.getDefault().post(compute());
        notifyDataSetChanged();
    }
}

十、用到的Bean類

一、GsonBean


	package com.gj.buycarej.bean;
	
	import java.util.List;
	
	public class GsonBean {
	
	    /**
	     * msg : 請求成功
	     * code : 0
	     * data : [{"list":[{"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":8,"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":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"},{"list":[{"bargainPrice":22.9,"createtime":"2017-10-03T23:53:28","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":10,"pid":26,"price":88,"pscid":2,"selected":0,"sellerid":3,"subhead":"三隻松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》","title":"三隻松鼠 堅果炒貨 零食奶油味 碧根果225g/袋"},{"bargainPrice":5599,"createtime":"2017-10-10T17:30:32","detailUrl":"https://item.m.jd.com/product/4824715.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n12/jfs/t7768/184/1153704394/148460/f42e1432/599a930fN8a85626b.jpg!q70.jpg","num":1,"pid":59,"price":5599,"pscid":40,"selected":0,"sellerid":3,"subhead":"遊戲本選擇4G獨顯,拒絕掉幀】升級版IPS全高清防眩光顯示屏,WASD方向鍵顏色加持,三大出風口立體散熱!","title":"戴爾DELL靈越遊匣15PR-6648B GTX1050 15.6英寸遊戲膝上型電腦(i5-7300HQ 8G 128GSSD+1T 4G獨顯 IPS)黑"}],"sellerName":"商家3","sellerid":"3"},{"list":[{"bargainPrice":11800,"createtime":"2017-10-14T21:48:08","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":7,"pid":60,"price":13888,"pscid":40,"selected":0,"sellerid":4,"subhead":"購買電腦辦公部分商品滿1元返火車票5元優惠券(返完即止)","title":"全球購 新款Apple MacBook Pro 蘋果膝上型電腦 銀色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家4","sellerid":"4"},{"list":[{"bargainPrice":22.9,"createtime":"2017-10-03T23:53:28","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":28,"price":599,"pscid":2,"selected":0,"sellerid":5,"subhead":"三隻松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》","title":"三隻松鼠 堅果炒貨 零食奶油味 碧根果225g/袋"}],"sellerName":"商家5","sellerid":"5"},{"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":29,"price":588,"pscid":2,"selected":0,"sellerid":6,"subhead":"三隻松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》","title":"三隻松鼠 堅果炒貨 零食奶油味 碧根果225g/袋"},{"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","num":1,"pid":62,"price":15999,"pscid":40,"selected":0,"sellerid":6,"subhead":"購買電腦辦公部分商品滿1元返火車票5元優惠券(返完即止)","title":"全球購 新款Apple MacBook Pro 蘋果膝上型電腦 銀色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家6","sellerid":"6"}]
	     */
	
	    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":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":8,"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 String sellerName;
	        private String sellerid;
	        private List<ListBean> list;
	        private boolean GropuCb;
	
	        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 boolean isGropuCb() {
	            return GropuCb;
	        }
	
	        public void setGropuCb(boolean gropuCb) {
	            GropuCb = gropuCb;
	        }
	
	        public static class ListBean {
	            /**
	             * bargainPrice : 11800.0
	             * 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 : 8
	             * pid : 57
	             * price : 5199.0
	             * 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)銀
	
	             */
	
	            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;
	            private boolean ChildCb;
	
	            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;
	            }
	
	            public boolean isChildCb() {
	                return ChildCb;
	            }
	
	            public void setChildCb(boolean childCb) {
	                ChildCb = childCb;
	            }
	        }
	    }
	}

二、MessageEvent

package com.gj.buycarej.bean;

public class MessageEvent {
    private boolean checked;
 
    public boolean isChecked() {
        return checked;
    }
 
    public void setChecked(boolean checked) {
        this.checked = checked;
    }
}

三、PriceAndCountEvent

package com.gj.buycarej.bean;

public class PriceAndCountEvent {
    private int price;
    private int count;
 
    public int getPrice() {
        return price;
    }
 
    public void setPrice(int price) {
        this.price = price;
    }
 
    public int getCount() {
        return count;
    }
 
    public void setCount(int count) {
        this.count = count;
    }
}