Retrofit+RXjava購物車

導入的依賴html

 compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.squareup.okhttp3:okhttp:3.9.0'
    compile 'com.google.code.gson:gson:2.8.1'
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'//retrofit依賴
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'//retrofit內部封裝的GSON
    compile "io.reactivex.rxjava2:rxjava:2.1.7"
    compile "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.facebook.fresco:fresco:0.12.0'
    compile 'com.facebook.fresco:animated-base-support:0.12.0'
    compile 'com.facebook.fresco:animated-webp:0.12.0'
    compile 'com.facebook.fresco:webpsupport:0.12.0'

  加入的權限java

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

  values下的attrsreact

 <declare-styleable name="AddDeleteView">
        <attr name="left_item" format="string"></attr>
        <attr name="right_item" format="string"></attr>
        <attr name="middle_item" format="string"></attr>
    </declare-styleable>

  activity_mainandroid

<?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.bawie.www.gou.view.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
    >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="購物車" />

        <TextView
            android:id="@+id/tv_bianji"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="編輯" />
    </RelativeLayout>

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

    </ExpandableListView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        android:padding="10dp">

        <CheckBox
            android:id="@+id/check_all"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:text="全選"
            android:textSize="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:gravity="center_vertical"
            android:text="總價:"
            android:textSize="15dp" />

        <TextView
            android:id="@+id/tv_zprce"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:gravity="center_vertical"
            android:text="0"
            android:textSize="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:gravity="center_vertical"
            android:text="數量:"
            android:textSize="15dp" />

        <TextView
            android:id="@+id/tv_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:text="0"
            android:textSize="15dp" />

        <Button
            android:id="@+id/btn_js"
            android:layout_width="80dp"
            android:layout_height="40dp"
            android:layout_gravity="right"
            android:background="#fc0109"
            android:text="結算"
            android:textSize="15dp" />
    </LinearLayout>


</LinearLayout>

  adddelete.xmlgit

<?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">

    <TextView
        android:id="@+id/tv_delete"
        android:layout_width="31dp"
        android:layout_height="31dp"
        android:background="#999999"
        android:gravity="center"
        android:text="-" />

    <EditText
        android:id="@+id/ed_num"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@null"
        android:gravity="center" />

    <TextView
        android:id="@+id/tv_add"
        android:layout_width="31dp"
        android:layout_height="31dp"
        android:background="#999999"
        android:gravity="center"
        android:text="+" />
</LinearLayout>

  gwc_goods_itemgithub

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <CheckBox
        android:id="@+id/check_gwc_goods"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:gravity="center_vertical" />

    <ImageView
        android:id="@+id/img_gwc_goods"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@mipmap/ic_launcher" />

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

        <TextView
            android:id="@+id/tv_gwc_goods"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="title" />

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

            <TextView
                android:id="@+id/tv_gwc_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="價格:"
                android:textColor="#fa0000" />
        </LinearLayout>

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

            <com.bawie.www.gou.view.AddDeleteView
                android:id="@+id/add_delete"
                android:layout_width="100dp"
                android:layout_height="30dp"
                android:layout_centerVertical="true"
                android:layout_marginRight="5dp"
                app:left_item="-"
                app:middle_item="1"
                app:right_item="+">

            </com.bawie.www.gou.view.AddDeleteView>

            <Button
                android:id="@+id/btn_gwc_delete"
                android:layout_width="110dp"
                android:layout_height="40dp"
                android:background="#f70496"
                android:layout_alignParentRight="true"
                android:gravity="center"
                android:text="刪除"
                android:textColor="#ffffff" />

        </RelativeLayout>
    </LinearLayout>
</LinearLayout>

  gwc_group_itemweb

<?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:background="#999999"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/check_gwc_group"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp" />

    <TextView
        android:id="@+id/tv_gwc_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="title"
        android:textSize="20dp" />

</LinearLayout>

  MainActivityapi

package com.bawie.www.gou.view;

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


import com.bawie.www.gou.R;
import com.bawie.www.gou.adapter.MyShopAdapter;
import com.bawie.www.gou.model.GoodsBean;
import com.bawie.www.gou.model.GroupBean;
import com.bawie.www.gou.model.IView;
import com.bawie.www.gou.model.ShopCar;
import com.bawie.www.gou.presenter.NewsPresenter;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements IView {

    @BindView(R.id.tv_bianji)
    TextView tvBianji;
    @BindView(R.id.exlist)
    ExpandableListView exlist;
    @BindView(R.id.check_all)
    public CheckBox checkAll;
    @BindView(R.id.tv_zprice)
    TextView price;
    @BindView(R.id.tv_count)
    TextView counts;
    @BindView(R.id.btn_js)
    Button btnJs;
    ArrayList<GroupBean> groupBeen = new ArrayList<>();
    ArrayList<ArrayList<GoodsBean>> goods = new ArrayList<>();
    private MyShopAdapter adapter;
    private boolean flagedit = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        NewsPresenter presenter = new NewsPresenter();
        presenter.attachView(this);
        Map<String, String> map = new HashMap<>();
        map.put("uid", "2606");
        presenter.getData(map);
        adapter = new MyShopAdapter(this, groupBeen, goods, this);
        exlist.setAdapter(adapter);
        for (int i = 0; i < adapter.getGroupCount(); i++) {
            exlist.expandGroup(i);
        }
        adapter.notifyDataSetChanged();
    }

    @OnClick({R.id.tv_bianji, R.id.check_all, R.id.btn_js})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_bianji:
                String trim = tvBianji.getText().toString().trim();
                if (trim.equals("編輯")) {
                    tvBianji.setText("完成");
                } else {
                    tvBianji.setText("編輯");
                }
                for (List<GoodsBean> i1 : goods) {
                    for (int r = 0; r < i1.size(); r++) {
                        i1.get(r).setBtn(flagedit);
                    }
                }
                flagedit = !flagedit;
                adapter.notifyDataSetChanged();
                break;
            case R.id.check_all:
                boolean checked = checkAll.isChecked();
                for (int i = 0; i < groupBeen.size(); i++) {
                    groupBeen.get(i).setGroupcheck(checked);
                }
                for (int q = 0; q < goods.size(); q++) {
                    ArrayList<GoodsBean> goodsBeen = goods.get(q);
                    for (int j = 0; j < goodsBeen.size(); j++) {
                        goodsBeen.get(j).setGoodscheck(checked);
                    }
                }
                changesum(goods);
                adapter.notifyDataSetChanged();
                break;
            case R.id.btn_js:
                int index = 0;
                for (int q = 0; q < goods.size(); q++) {
                    ArrayList<GoodsBean> goodsBeen = goods.get(q);
                    for (int j = 0; j < goodsBeen.size(); j++) {
                        boolean goodscheck = goodsBeen.get(j).isGoodscheck();
                        if (goodscheck) {
                            index++;
                        }
                    }
                }
                if (index == 0) {
                    Toast.makeText(this, "請選擇商品,謝謝", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "錢就是另外一回事了", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    public void OnSuccess(Object o) {
        if (o != null) {
            if (o instanceof List) {
                List<ShopCar.DataBean> data = (List<ShopCar.DataBean>) o;
                for (int i = 0; i < data.size(); i++) {
                    groupBeen.add(new GroupBean(false, data.get(i).getSellerName(), data.get(i).getSellerid()));
                    List<ShopCar.DataBean.ListBean> list = data.get(i).getList();
                    ArrayList<GoodsBean> goodsBeen = new ArrayList<>();
                    for (int j = 0; j < list.size(); j++) {
                        goodsBeen.add(new GoodsBean(false, list.get(j).getBargainPrice(), list.get(j).getImages(), list.get(j).getTitle(), list.get(j).getSubhead(), list.get(j).getNum(), list.get(j).getPid()));
                    }
                    goods.add(goodsBeen);
                }
                for (int i = 0; i < adapter.getGroupCount(); i++) {
                    exlist.expandGroup(i);
                }
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void OnFailed(Exception e) {
        Toast.makeText(this, "shibai", Toast.LENGTH_SHORT).show();
    }

    DecimalFormat df = new DecimalFormat("######0.00");

    public void changesum(ArrayList<ArrayList<GoodsBean>> childBeen) {
        int count = 0;
        double sum = 0;
        for (List<GoodsBean> i1 : childBeen) {
            for (int r = 0; r < i1.size(); r++) {
                boolean childCb1 = i1.get(r).isGoodscheck();
                if (childCb1) {
                    double price = i1.get(r).getBargainPrice();
                    int num = i1.get(r).getNum();
                    sum += price * num;
                    count++;
                }
            }
        }
        price.setText("¥" + df.format(sum));
        counts.setText(count + "");
    }

    public void deleteShop(int pid) {
        Toast.makeText(this, "aadas", Toast.LENGTH_SHORT).show();
    }
}

  View層的AddDeleteViewapp

package com.bawie.www.gou.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bawie.www.gou.R;


public class AddDeleteView extends LinearLayout {
    private OnAddDelClickListener listener;
    private EditText etNumber;

    //對外提供一個點擊的回調接口
    public interface OnAddDelClickListener {
        void onAddClick(View v);

        void onDelClick(View v);
    }

    public void setOnAddDelClickListener(OnAddDelClickListener listener) {
        if (listener != null) {
            this.listener = listener;
        }
    }

    public AddDeleteView(Context context) {
        this(context, null);
    }

    public AddDeleteView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AddDeleteView(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.adddelete, this);
        TextView txtDelete = (TextView) findViewById(R.id.tv_delete);
        TextView txtAdd = (TextView) findViewById(R.id.tv_add);
        etNumber = (EditText) findViewById(R.id.ed_num);


        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AddDeleteView);

        String leftText = typedArray.getString(R.styleable.AddDeleteView_left_item);
        String rightText = typedArray.getString(R.styleable.AddDeleteView_right_item);
        String middleText = typedArray.getString(R.styleable.AddDeleteView_middle_item);

        txtDelete.setText(leftText);
        txtAdd.setText(rightText);
        etNumber.setText(middleText);

        //回收
        typedArray.recycle();


        txtDelete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onDelClick(view);
            }
        });

        txtAdd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onAddClick(view);
            }
        });

    }

    //對外提供一個修改數字的方法
    public void setNumber(int number) {
        if (number > 0) {
            etNumber.setText(number + "");
        }
    }

    //對外提供一個獲取當前數字的方法
    public int getNumber() {
        String string = etNumber.getText().toString();
        int i = Integer.parseInt(string);
        return i;
    }
}

  presenter層的NewsPresenteride

package com.bawie.www.gou.presenter;


import com.bawie.www.gou.model.IPresenter;
import com.bawie.www.gou.model.IView;
import com.bawie.www.gou.model.Model;
import com.bawie.www.gou.model.ShopCar;

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


import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;


/**
 * Created by Administrator on 2017/12/16 0016.
 */

public class NewsPresenter implements IPresenter {
    private IView iView;
    private DisposableSubscriber<ShopCar> subscriber;

    public void attachView(IView iView) {
        this.iView = iView;
    }

    @Override
    public void getData(Map<String, String> map) {
        Model model = new Model(this);
        model.getData(map);
    }

    public void detachView() {
        if (subscriber != null) {
            //若是該資源已被處理,則可一次性返回true。若是沒有被處理返回false
            if (!subscriber.isDisposed()) {
                subscriber.dispose();
            }
        }

    }

    public void get(Flowable<ShopCar> flowable) {
        subscriber = flowable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableSubscriber<ShopCar>() {
                    @Override
                    public void onNext(ShopCar listMessageBean) {
                        if (listMessageBean != null) {
                            List<ShopCar.DataBean> data = listMessageBean.getData();
                            if (data != null) {
                                iView.OnSuccess(data);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        iView.OnFailed(new Exception(t));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}

  model層的APIService

package com.bawie.www.gou.model;

import java.util.Map;

import io.reactivex.Flowable;
import retrofit2.http.GET;
import retrofit2.http.QueryMap;

/**
 * Created by Administrator on 2017/12/16 0016.
 */

public interface APIService {
    //http://120.27.23.105/product/getCarts
    @GET("product/getCarts")
    Flowable<ShopCar> getNews(@QueryMap Map<String, String> map);
}

  Model層的GoodsBean

package com.bawie.www.gou.model;

/**
 * 做者 陳飛 on 2017/11/21 0021.
 */

public class GoodsBean {
    private boolean goodscheck;
    private double bargainPrice;
    private String images;
    private String title;
    private String subhead;
    private int num;
    private boolean btn;
    private int pid;

    public GoodsBean(boolean goodscheck, double bargainPrice, String images, String title, String subhead, int num, boolean btn) {
        this.goodscheck = goodscheck;
        this.bargainPrice = bargainPrice;
        this.images = images;
        this.title = title;
        this.subhead = subhead;
        this.num = num;
        this.btn = btn;
    }

    public GoodsBean(boolean goodscheck, double bargainPrice, String images, String title, String subhead, int num, int pid) {
        this.goodscheck = goodscheck;
        this.bargainPrice = bargainPrice;
        this.images = images;
        this.title = title;
        this.subhead = subhead;
        this.num = num;
        this.pid = pid;
    }

    public int getPid() {
        return pid;
    }

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

    public boolean isBtn() {
        return btn;
    }

    public void setBtn(boolean btn) {
        this.btn = btn;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public boolean isGoodscheck() {
        return goodscheck;
    }

    public void setGoodscheck(boolean goodscheck) {
        this.goodscheck = goodscheck;
    }

    public double getBargainPrice() {
        return bargainPrice;
    }

    public void setBargainPrice(double bargainPrice) {
        this.bargainPrice = bargainPrice;
    }

    public String getImages() {
        return images;
    }

    public void setImages(String images) {
        this.images = images;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSubhead() {
        return subhead;
    }

    public void setSubhead(String subhead) {
        this.subhead = subhead;
    }

    @Override
    public String toString() {
        return "GoodsBean{" +
                "goodscheck=" + goodscheck +
                ", bargainPrice=" + bargainPrice +
                ", images='" + images + '\'' +
                ", title='" + title + '\'' +
                ", subhead='" + subhead + '\'' +
                ", num=" + num +
                ", btn=" + btn +
                '}';
    }
}

  GroupBean

package com.bawie.www.gou.model;

/**
 * 做者 陳飛 on 2017/11/21 0021.
 */

public class GroupBean {
    private boolean groupcheck;
    private String sellerName;
    private String sellerid;

    public GroupBean(boolean groupcheck, String sellerName, String sellerid) {
        this.groupcheck = groupcheck;
        this.sellerName = sellerName;
        this.sellerid = sellerid;
    }

    public boolean isGroupcheck() {
        return groupcheck;
    }

    public void setGroupcheck(boolean groupcheck) {
        this.groupcheck = groupcheck;
    }

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

    @Override
    public String toString() {
        return "GroupBean{" +
                "groupcheck=" + groupcheck +
                ", sellerName='" + sellerName + '\'' +
                ", sellerid=" + sellerid +
                '}';
    }
}

  IModel

package com.bawie.www.gou.model;

import java.util.Map;

/**
 * Created by Administrator on 2017/12/16 0016.
 */

public interface IModel {
    void getData(Map<String, String> map);
}

  IPresenter

package com.bawie.www.gou.model;

import java.util.Map;

/**
 * Created by Administrator on 2017/12/16 0016.
 */

public interface IPresenter {
    void getData(Map<String, String> map);
}

  IView

package com.bawie.www.gou.model;

/**
 * Created by Administrator on 2017/12/16 0016.
 */

public interface IView {
    void OnSuccess(Object o);

    void OnFailed(Exception e);
}

  Model

package com.bawie.www.gou.model;



import com.bawie.www.gou.presenter.NewsPresenter;

import java.util.Map;

import io.reactivex.Flowable;

/**
 * Created by Administrator on 2017/12/16 0016.
 */

public class Model implements IModel {
    private NewsPresenter presenter;

    public Model(NewsPresenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void getData(Map<String, String> map) {
        Flowable<ShopCar> flowable = RetrofitUtils.getInstance().getApiService().getNews(map);
        presenter.get(flowable);
    }
}

  RetrofitUtils

package com.bawie.www.gouwu.utils;

import com.bawie.www.gouwu.model.APIService;

import java.io.IOException;
import java.util.logging.Logger;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
* Created by 楊文倩 on 2017/12/19.
*/

public class RetrofitUtils {
private static volatile RetrofitUtils instance;
private final Retrofit retrofit;


private RetrofitUtils() {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Logger())
.build();
retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://120.27.23.105/")
.build();
}

public static RetrofitUtils getInstance() {
if (instance == null) {
synchronized (RetrofitUtils.class) {
if (instance == null) {
instance = new RetrofitUtils();
}
}
}
return instance;
}

public APIService getApiService() {
APIService apiService = retrofit.create(APIService.class);
return apiService;
}
class Logger 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);
}
}
}

  ShopCar

package com.bawie.www.gou.model;

import java.util.List;

/**
 * 做者 陳飛 on 2017/11/21 0021.
 */

public class ShopCar {

    /**
     * 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":2,"pid":24,"price":288,"pscid":2,"selected":0,"sellerid":1,"subhead":"三隻松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》","title":"三隻松鼠 堅果炒貨 零食奶油味 碧根果225g/袋"}],"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 黑)"},{"bargainPrice":6666,"createtime":"2017-10-10T16:01:31","detailUrl":"https://item.m.jd.com/product/5089273.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t8284/363/1326459580/71585/6d3e8013/59b857f2N6ca75622.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9346/182/1406837243/282106/68af5b54/59b8480aNe8af7f5c.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8434/54/1359766007/56140/579509d9/59b85801Nfea207db.jpg!q70.jpg","num":1,"pid":46,"price":234,"pscid":39,"selected":0,"sellerid":2,"subhead":"【iPhone新品上市】新一代iPhone,讓智能看起來更不同","title":"Apple iPhone 8 Plus (A1864) 64GB 金色 移動聯通電信4G手機"}],"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":85,"pid":10,"price":555.55,"pscid":1,"selected":0,"sellerid":3,"subhead":"每一箇中秋都不能簡單,不管身在何處,你總須要一塊餅讓生活更圓滿,京東月餅讓愛更圓滿京東自營,閃電配送,更多驚喜,快用手指戳一下","title":"北京稻香村 稻香村中秋節月餅 老北京月餅禮盒655g"}],"sellerName":"商家3","sellerid":"3"},{"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":61,"price":14999,"pscid":40,"selected":0,"sellerid":5,"subhead":"購買電腦辦公部分商品滿1元返火車票5元優惠券(返完即止)","title":"全球購 新款Apple MacBook Pro 蘋果筆記本電腦 銀色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家5","sellerid":"5"},{"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":100,"price":2200,"pscid":112,"selected":0,"sellerid":11,"subhead":"針織針織閃閃閃亮你的眼","title":"維邇旎 2017秋冬新款長袖針織連衣裙韓版氣質中長款名媛包臀A字裙 zx179709 黑色 XL"}],"sellerName":"商家11","sellerid":"11"},{"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"}]
     */

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

    @Override
    public String toString() {
        return "ShopCar{" +
                "msg='" + msg + '\'' +
                ", code='" + code + '\'' +
                ", data=" + data +
                '}';
    }

    public static class DataBean {
        /**
         * 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":2,"pid":24,"price":288,"pscid":2,"selected":0,"sellerid":1,"subhead":"三隻松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》","title":"三隻松鼠 堅果炒貨 零食奶油味 碧根果225g/袋"}]
         * sellerName : 商家1
         * sellerid : 1
         */

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

        @Override
        public String toString() {
            return "DataBean{" +
                    "sellerName='" + sellerName + '\'' +
                    ", sellerid='" + sellerid + '\'' +
                    ", list=" + list +
                    '}';
        }

        public static class ListBean {
            /**
             * 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 : 2
             * pid : 24
             * price : 288.0
             * pscid : 2
             * selected : 0
             * sellerid : 1
             * subhead : 三隻松鼠零食特惠,專區滿99減50,滿199減100,火速搶購》
             * title : 三隻松鼠 堅果炒貨 零食奶油味 碧根果225g/袋
             */

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

            @Override
            public String toString() {
                return "ListBean{" +
                        "bargainPrice=" + bargainPrice +
                        ", createtime='" + createtime + '\'' +
                        ", detailUrl='" + detailUrl + '\'' +
                        ", images='" + images + '\'' +
                        ", num=" + num +
                        ", pid=" + pid +
                        ", price=" + price +
                        ", pscid=" + pscid +
                        ", selected=" + selected +
                        ", sellerid=" + sellerid +
                        ", subhead='" + subhead + '\'' +
                        ", title='" + title + '\'' +
                        '}';
            }
        }
    }
}

  adapter裏的MyShopAdapter

package com.bawie.www.gou.adapter;

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 android.widget.Toast;

import com.bawie.www.gou.R;
import com.bawie.www.gou.model.GoodsBean;
import com.bawie.www.gou.model.GroupBean;
import com.bawie.www.gou.view.AddDeleteView;
import com.bawie.www.gou.view.MainActivity;
import com.bumptech.glide.Glide;

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

public class MyShopAdapter extends BaseExpandableListAdapter {
    Context context;
    ArrayList<GroupBean> groupBeen;
    ArrayList<ArrayList<GoodsBean>> goods;
    MainActivity mainActivity;

    public MyShopAdapter(Context context, ArrayList<GroupBean> groupBeen, ArrayList<ArrayList<GoodsBean>> goods, MainActivity mainActivity) {
        this.context = context;
        this.groupBeen = groupBeen;
        this.goods = goods;
        this.mainActivity = mainActivity;
    }

    @Override
    public int getGroupCount() {
        if (groupBeen != null) {
            return groupBeen.size();
        }
        return 0;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        if (goods.get(groupPosition) != null) {
            return goods.get(groupPosition).size();
        }
        return 0;
    }

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

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return goods.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 = View.inflate(context, R.layout.gwc_group_item, null);
        final CheckBox check_group = (CheckBox) view.findViewById(R.id.check_gwc_group);
        TextView group = (TextView) view.findViewById(R.id.tv_gwc_group);
        check_group.setChecked(groupBeen.get(groupPosition).isGroupcheck());
        group.setText(groupBeen.get(groupPosition).getSellerName());
        check_group.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GroupBean group = groupBeen.get(groupPosition);
                group.setGroupcheck(check_group.isChecked());
                for (int j = 0; j < groupBeen.size(); j++) {
                    boolean groupCheck = groupBeen.get(j).isGroupcheck();
                    if (!groupCheck) {
                        mainActivity.checkAll.setChecked(false);
                        break;
                    } else {
                        mainActivity.checkAll.setChecked(true);
                    }
                }
                ArrayList<GoodsBean> goodsBeen = goods.get(groupPosition);
                for (int i = 0; i < goodsBeen.size(); i++) {
                    goodsBeen.get(i).setGoodscheck(check_group.isChecked());
                }
                //計算價格
                mainActivity.changesum(goods);
                notifyDataSetChanged();
            }
        });
        return view;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        View view = View.inflate(context, R.layout.gwc_goods_item, null);
        TextView tv_goods = (TextView) view.findViewById(R.id.tv_gwc_goods);
        TextView price = (TextView) view.findViewById(R.id.tv_gwc_price);
        final CheckBox check_goods = (CheckBox) view.findViewById(R.id.check_gwc_goods);
        ImageView img_goods = (ImageView) view.findViewById(R.id.img_gwc_goods);
        Button btn_delete = (Button) view.findViewById(R.id.btn_gwc_delete);
        final AddDeleteView adv = (AddDeleteView) view.findViewById(R.id.add_delete);
        tv_goods.setText(goods.get(groupPosition).get(childPosition).getTitle());
        price.setText(goods.get(groupPosition).get(childPosition).getBargainPrice() + "");
        check_goods.setChecked(goods.get(groupPosition).get(childPosition).isGoodscheck());
        String images = goods.get(groupPosition).get(childPosition).getImages();
        String[] split = images.split("\\|");
        Glide.with(img_goods.getContext()).load(split[0]).into(img_goods);
        adv.setNumber(goods.get(groupPosition).get(childPosition).getNum());
        if (goods.get(groupPosition).get(childPosition).isBtn()) {
            btn_delete.setVisibility(View.VISIBLE);
        } else {
            btn_delete.setVisibility(View.INVISIBLE);
        }
        adv.setOnAddDelClickListener(new AddDeleteView.OnAddDelClickListener() {
            @Override
            public void onAddClick(View v) {
                int number = adv.getNumber();
                number++;
                adv.setNumber(number);
                goods.get(groupPosition).get(childPosition).setNum(number);
                mainActivity.changesum(goods);
            }

            @Override
            public void onDelClick(View v) {
                int number = adv.getNumber();
                if (number > 1) {
                    number--;
                }
                adv.setNumber(number);
                goods.get(groupPosition).get(childPosition).setNum(number);
                mainActivity.changesum(goods);
            }
        });
        btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mainActivity.deleteShop(goods.get(groupPosition).get(childPosition).getPid());
                int size = goods.get(groupPosition).size();
                if (goods.get(groupPosition).get(childPosition).isGoodscheck()) {
                    if (size == 1) {
                        goods.remove(groupPosition);
                        groupBeen.remove(groupPosition);
                    } else {
                        goods.get(groupPosition).remove(childPosition);
                    }
                    mainActivity.changesum(goods);
                    notifyDataSetChanged();
                } else {
                    Toast.makeText(context, "請選擇商品。。。", Toast.LENGTH_SHORT).show();
                }
            }
        });
        check_goods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //定義一個默認flag
                boolean flag = false;
                //得到當前二級列表複選框的狀態
                boolean cchecked = check_goods.isChecked();
                //把當前狀態存儲到二級列表List集合裏面
                goods.get(groupPosition).get(childPosition).setGoodscheck(cchecked);

                //循環遍歷二級列表List集合
                for (List<GoodsBean> i1 : goods) {
                    // 按照全部二級列表的item的個數進行循環遍歷
                    for (int r = 0; r < i1.size(); r++) {
                        //獲取當前二級列表的狀態
                        boolean childCb1 = i1.get(r).isGoodscheck();
                        //取反設置 若是爲true改成false 若是爲false改成true
                        if (!childCb1) {
                            //若是當前二級列表中有一條複選框是false  全選爲false
                            mainActivity.checkAll.setChecked(false);
                            //若是當前二級列表中有一條複選框是false  一級列表爲false
                            groupBeen.get(groupPosition).setGroupcheck(false);
                            //flag爲true跳出循環
                            flag = true;
                            break;
                        } else {
                            //若是全部的二級列表都爲true  全選爲true
                            mainActivity.checkAll.setChecked(true);
                            //若是全部的二級列表都爲true  一級列表爲true
                            groupBeen.get(groupPosition).setGroupcheck(true);
                        }
                    }
                    //falg爲true時跳出循環
                    if (flag) {
                        break;
                    }
                }
                //當前二級列表的總長度
                int size = goods.get(groupPosition).size();
                //按照當前二級列表的總長度循環
                for (int x = 0; x < size; x++) {
                    //得到當前二級列表中每個item的選中狀態
                    boolean childCb1 = goods.get(groupPosition).get(x).isGoodscheck();
                    //判斷
                    if (!childCb1) {
                        //有一個flase 一級列表就設置false  跳出循環
                        groupBeen.get(groupPosition).setGroupcheck(false);
                        break;
                    } else {
                        groupBeen.get(groupPosition).setGroupcheck(true);
                    }
                }
                //計算價格
                mainActivity.changesum(goods);
                //刷新適配器
                notifyDataSetChanged();
            }
        });
        return view;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }
}
相關文章
相關標籤/搜索