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

購物車---二級列表

主佈局—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"
    tools:context=".MainActivity">

    <ExpandableListView
        android:id="@+id/el_cart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="60dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true">

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全選" />

        <TextView
            android:id="@+id/text_total_price"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="20dp"
            android:text="合計:¥0.00" />

        <Button
            android:id="@+id/btn_cart_pay"
            android:layout_width="100dp"
            android:layout_height="match_parent"
            android:text="去結算(0)" />
    </LinearLayout>
</RelativeLayout>

加減號 —add_sub_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="70dp"
    android:layout_height="40dp"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/sub_tv"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:text="-"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/number_tv"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginLeft="2dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:text="1" />

    <TextView
        android:id="@+id/add_tv"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginLeft="2dp"
        android:layout_weight="1"
        android:background="#ffffff"
        android:gravity="center"
        android:text="+"
        android:textSize="16sp" />
</LinearLayout>

組類佈局(商家)—parent_item

<?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="50dp"
    android:gravity="center_vertical">

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

    <TextView
        android:id="@+id/seller_name_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="hjhkhk"/>
</LinearLayout>

子類佈局(商品)—child_item

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

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

    <ImageView
        android:id="@+id/product_image"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_marginLeft="20dp"
        android:scaleType="centerCrop"
        android:src="@color/colorPrimary" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:id="@+id/product_title_name_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="2"
            android:text="商品標題" />

        <TextView
            android:id="@+id/product_price_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="¥0.0" />
    </LinearLayout>

    <wanghuiqi.bawie.com.whq_shopper.MyAppSub
        android:id="@+id/add_sub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp" />
</LinearLayout>

自定義加減器 MyAppSub

package wanghuiqi.bawie.com.whq_shopper;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.awt.font.NumericShaper;

public class MyAppSub extends LinearLayout implements View.OnClickListener {

    private TextView add_tv;
    private TextView sub_tv;
    private TextView number_tv;
    private int number = 1;

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

    public MyAppSub(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyAppSub(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View view = inflate(context, R.layout.add_sub_item, this);
        add_tv = view.findViewById(R.id.add_tv);
        sub_tv = view.findViewById(R.id.sub_tv);
        number_tv = view.findViewById(R.id.number_tv);

        add_tv.setOnClickListener(this);
        sub_tv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sub_tv:
                if (number > 1) {
                    --number;
                    number_tv.setText(number + "");
                    if (mOnNumberChangeListener != null) {
                        mOnNumberChangeListener.onNumberChange(number);
                    }
                } else {
                    Toast.makeText(getContext(), "不能再少了", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.add_tv:
                ++number;
                number_tv.setText(number + "");
                if (mOnNumberChangeListener != null) {
                    mOnNumberChangeListener.onNumberChange(number);
                }
                break;
        }
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
        number_tv.setText(number + "");
    }

    //建立介面
    public interface OnNumberChangeListener {
        void onNumberChange(int num);
    }

    //宣告介面名
    OnNumberChangeListener mOnNumberChangeListener;

    //暴露方法
    public void setOnNumberChangeListener(OnNumberChangeListener onNumberChangeListener) {
        mOnNumberChangeListener = onNumberChangeListener;
    }
}

MyShopAdapter

package wanghuiqi.bawie.com.whq_shopper;

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

import com.squareup.picasso.Picasso;

import java.util.List;

import wanghuiqi.bawie.com.whq_shopper.bean.Shop;

public class MyShopAdapter extends BaseExpandableListAdapter {
    private List<Shop.DataBean> shopData;

    public MyShopAdapter(List<Shop.DataBean> shopData) {
        this.shopData = shopData;
    }

    //1、決定多少鈕
    @Override
    public int getGroupCount() {
        //三元運算子,提供程式執行效率
        return shopData.size();
    }

    //2、一個組裡面有多少個子條目
    @Override
    public int getChildrenCount(int groupPosition) {
        return shopData.get(groupPosition).getList().size();
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        //3、
        Shop.DataBean dataBean = shopData.get(groupPosition);
        Parentholder parentholder;
        if (convertView == null) {
            convertView = View.inflate(parent.getContext(), R.layout.parent_item, null);
            parentholder = new Parentholder(convertView);
            convertView.setTag(parentholder);
        } else {
            parentholder = (Parentholder) convertView.getTag();
        }
        //4、商家名字
        parentholder.seller_name_tv.setText(dataBean.getSellerName());
        //5、根據當前商家的所有商品,確定商家的checkbox是否選中
        boolean currentSellerAllSelected = isCurrentSellerAllSelect(groupPosition);
        //5.2、根據boolean判斷是否選中
        parentholder.seller_box.setChecked(currentSellerAllSelected);
        //6、設定點選checkbox的點選事件,介面回撥
        parentholder.seller_box.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnCartListChangeListener != null) {
                    mOnCartListChangeListener.onSellerCheckedChange(groupPosition);
                }
            }
        });
        return convertView;
    }

    //8、子條目佈局
    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        //子條目所有的資料
        Shop.DataBean dataBean = shopData.get(groupPosition);
        List<Shop.DataBean.ListBean> list = dataBean.getList();
        //拿到list集合裡具體商品
        Shop.DataBean.ListBean listBean = list.get(childPosition);
        Childholder childholder;
        if (convertView == null) {
            convertView = View.inflate(parent.getContext(), R.layout.child_item, null);
            childholder = new Childholder(convertView);
            convertView.setTag(childholder);
        } else {
            childholder = (Childholder) convertView.getTag();
        }

        //獲取圖片Picasso
        String images = listBean.getImages();
        String[] strings = images.split("!");
        Picasso.with(parent.getContext()).load(strings[0]).into(childholder.product_image);
        //9、設定商品名字
        childholder.product_title_name_tv.setText(listBean.getTitle());
        //9.1設定商品單價
        childholder.product_price_tv.setText(listBean.getPrice() + "");
        //9.2設定商品複選框是否選中
        childholder.child_box.setChecked(listBean.getSelected() == 1);
        //9.3設定組合式自定義控制元件內部的數量
        childholder.add_sub.setNumber(listBean.getNum());

        //10、設定商品checkbox的點選事件,介面回撥
        childholder.child_box.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnCartListChangeListener != null) {
                    mOnCartListChangeListener.onProductCheckedChange(groupPosition, childPosition);
                }
            }
        });
        //11、設定商品數量的點選事件,介面回撥
        childholder.add_sub.setOnNumberChangeListener(new MyAppSub.OnNumberChangeListener() {
            @Override
            public void onNumberChange(int num) {
                if (mOnCartListChangeListener != null) {
                    mOnCartListChangeListener.onProductNumberChange(groupPosition, childPosition, num);
                }
            }
        });

        return convertView;
    }

    //5.1、判斷當前商家所有商品是否被選中
    public boolean isCurrentSellerAllSelect(int groupPosition) {
        //拿到對應的資料
        Shop.DataBean dataBean = shopData.get(groupPosition);
        //拿到商家的所又商品資料,是一個集合
        List<Shop.DataBean.ListBean> list = dataBean.getList();
        for (Shop.DataBean.ListBean listBean : list) {
            //判斷這個組的所有商品是否被選中,如有一個未選中就都沒選中
            if (listBean.getSelected() == 0) {
                return false;
            }
        }
        return true;
    }

    //12、底部有一個全選按鈕的邏輯,判斷
    public boolean isAllProductsSelected() {
        for (int x = 0; x < shopData.size(); x++) {
            Shop.DataBean dataBean = shopData.get(x);
            List<Shop.DataBean.ListBean> list = dataBean.getList();
            for (int j = 0; j < list.size(); j++) {
                //判斷組的所有商品是否被選中
                if (list.get(j).getSelected() == 0) {
                    return false;
                }
            }
        }
        return true;
    }

    //13、計算商品總數量
    public int calculateTotalNumber() {
        int totalNumber = 0;
        for (int x = 0; x < shopData.size(); x++) {
            Shop.DataBean dataBean = shopData.get(x);
            List<Shop.DataBean.ListBean> list = dataBean.getList();
            for (int j = 0; j < list.size(); j++) {
                //商品數量只算選中
                if (list.get(j).getSelected() == 1) {
                    //拿到商品的數量
                    int num = list.get(j).getNum();
                    totalNumber += num;
                }
            }
        }
        return totalNumber;
    }

    //14、計算所有商品的總價格
    public float calculateTotalPrice() {
        float totalPrice = 0;
        for (int x = 0; x < shopData.size(); x++) {
            Shop.DataBean dataBean = shopData.get(x);
            List<Shop.DataBean.ListBean> list = dataBean.getList();
            for (int j = 0; j < list.size(); j++) {
                //商品價格只算選中
                if (list.get(j).getSelected() == 1) {
                    //拿到商品的數量
                    double price = list.get(j).getPrice();
                    int num = list.get(j).getNum();
                    totalPrice += price * num;
                }
            }
        }
        return totalPrice;
    }

    /////////根據使用者選擇,改變選框裡的狀態//////
    //15、當商品組全選框點選時,更新所有商品全選框的狀態
    public void changSellerAllProduct(int groupPosition, boolean isSelected) {
        Shop.DataBean dataBean = shopData.get(groupPosition);
        List<Shop.DataBean.ListBean> list = dataBean.getList();
        for (int x = 0; x < list.size(); x++) {
            Shop.DataBean.ListBean listBean = list.get(x);
            listBean.setSelected(isSelected ? 1 : 0);
        }
    }

    //16、當商家子條目的全選框選中時,更新全選框的狀態
    public void changeChildProduct(int groupPosition, int childPosition) {
        Shop.DataBean dataBean = shopData.get(groupPosition);
        List<Shop.DataBean.ListBean> list = dataBean.getList();
        Shop.DataBean.ListBean listBean = list.get(childPosition);
        listBean.setSelected(listBean.getSelected() == 0 ? 1 : 0);
    }

    //17、當最底部全選框選中時,更新所有商品全選框的狀態
    public void chageAllProduct(boolean selected) {
        for (int x = 0; x < shopData.size(); x++) {
            Shop.DataBean dataBean = shopData.get(x);
            List<Shop.DataBean.ListBean> list = dataBean.getList();
            for (int j = 0; j < list.size(); j++) {
                list.get(j).setSelected(selected ? 1 : 0);
            }
        }
    }

    //18、當加減器被點選時,改變當前商品的數量 引數1:商家 引數2:商品 引數3:改變具體的數量
    public void changeProductNumber(int groupPosition, int childPosition, int number) {
        Shop.DataBean dataBean = shopData.get(groupPosition);
        List<Shop.DataBean.ListBean> list = dataBean.getList();
        Shop.DataBean.ListBean listBean = list.get(childPosition);
        listBean.setNum(number);
    }


    ////////建立Viewholder//////
    public static class Parentholder {

        public CheckBox seller_box;
        public TextView seller_name_tv;

        public Parentholder(View rootView) {
            this.seller_box = rootView.findViewById(R.id.seller_box);
            this.seller_name_tv = rootView.findViewById(R.id.seller_name_tv);
        }
    }

    public static class Childholder {

        public CheckBox child_box;
        public ImageView product_image;
        public TextView product_title_name_tv;
        public TextView product_price_tv;
        public MyAppSub add_sub;

        public Childholder(View rootView) {
            this.child_box = rootView.findViewById(R.id.child_box);
            this.product_image = rootView.findViewById(R.id.product_image);
            this.product_title_name_tv = rootView.findViewById(R.id.product_title_name_tv);
            this.product_price_tv = rootView.findViewById(R.id.product_price_tv);
            this.add_sub = rootView.findViewById(R.id.add_sub);
        }
    }

    //7、建立介面
    public interface onCartListChangeListener {
        //* 當商家的checkbox點選時回撥*//*
        void onSellerCheckedChange(int groupPosition);

        //*當點選子條目商品的checkbox回撥*//*
        void onProductCheckedChange(int groupPosition, int childPosition);

        //*當點選加減按鈕的回撥*//*
        void onProductNumberChange(int groupPosition, int childPosition, int number);
    }

    //7.1宣告介面名
    private onCartListChangeListener mOnCartListChangeListener;

    //7.2暴露方法(設定監聽加減按鈕,商家的複選框,子條目的複選框)
    public void setOnCartListChangeListener(onCartListChangeListener onCartListChangeListener) {
        mOnCartListChangeListener = onCartListChangeListener;
    }


    //////////不用管這些////////
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return null;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return null;
    }

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

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return 0;
    }

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

MainActivity

package wanghuiqi.bawie.com.whq_shopper;

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

import com.google.gson.Gson;

import java.security.PublicKey;
import java.util.HashMap;
import java.util.List;

import wanghuiqi.bawie.com.whq_shopper.bean.Shop;
import wanghuiqi.bawie.com.whq_shopper.model.HttpUtils;
import wanghuiqi.bawie.com.whq_shopper.presenter.ShopPresenter;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ExpandableListView el_cart;
    private CheckBox box_all_select;
    private TextView text_total_price;
    private Button btn_cart_pay;
    private MyShopAdapter shopAdapter;
    private String url = "http://www.zhaoapi.cn/product/getCarts?uid=71";
    //post介面地址
    // private String url = "http://www.zhaoapi.cn/product/getCarts";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1、初始化控制元件
        initView();
        //2、資料
        initData();
    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("uid", "71");

        ShopPresenter shopPresenter = new ShopPresenter();
        shopPresenter.ShopData(url);
        shopPresenter.setOnShopInterface(new ShopPresenter.OnShopInterface() {
            @Override
            public void failed(Exception e) {

            }

            @Override
            public void success(List<Shop.DataBean> shopData) {
                //2.2把資料給adapter,建立adapter物件
                shopAdapter = new MyShopAdapter(shopData);

                //2.3對介面卡設定監聽,金婷加減按鈕,商家的複選框,子條目改變
                shopAdapter.setOnCartListChangeListener(new MyShopAdapter.onCartListChangeListener() {
                    //2.4當商家被點選時
                    @Override
                    public void onSellerCheckedChange(int groupPosition) {
                        boolean currentSellerAllSelect = shopAdapter.isCurrentSellerAllSelect(groupPosition);
                        shopAdapter.changSellerAllProduct(groupPosition, !currentSellerAllSelect);
                        shopAdapter.notifyDataSetChanged();
                        //3、重新整理底部
                        refreshAllShop();
                    }

                    //當點選子條目商品的checkbox回撥
                    @Override
                    public void onProductCheckedChange(int groupPosition, int childPosition) {
                        shopAdapter.changeChildProduct(groupPosition, childPosition);
                        shopAdapter.notifyDataSetChanged();
                        refreshAllShop();
                    }

                    @Override
                    public void onProductNumberChange(int groupPosition, int childPosition, int number) {
                        shopAdapter.changeProductNumber(groupPosition, childPosition, number);
                        shopAdapter.notifyDataSetChanged();
                        refreshAllShop();
                    }
                });
                //設定adapter物件
                el_cart.setAdapter(shopAdapter);
                //展開二級列表
                for (int x = 0; x < shopData.size(); x++) {
                    el_cart.expandGroup(x);
                }
            }
        });
    }

    //4、底部全選框的點選事件設定
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.box_all_select:
                boolean allProductsSelected = shopAdapter.isAllProductsSelected();
                shopAdapter.chageAllProduct(!allProductsSelected);
                shopAdapter.notifyDataSetChanged();
                //重新整理底部的資料顯示
                refreshAllShop();
                break;
        }
    }

    //重新整理底部
    private void refreshAllShop() {
        //3.1判斷是否所有的商品都被選中
        boolean allProductsSelected = shopAdapter.isAllProductsSelected();
        //3.2把這個值設定checkbox
        box_all_select.setChecked(allProductsSelected);
        //3.3計算總計
        float totalPrice = shopAdapter.calculateTotalPrice();
        text_total_price.setText("總計" + totalPrice);
        //3.4計算總數量
        int totalNumber = shopAdapter.calculateTotalNumber();
        btn_cart_pay.setText("去結算(" + totalNumber + ")");
    }

    //初始化控制元件
    private void initView() {
        el_cart = findViewById(R.id.el_cart);
        box_all_select = findViewById(R.id.box_all_select);
        text_total_price = findViewById(R.id.text_total_price);
        btn_cart_pay = findViewById(R.id.btn_cart_pay);

        //給全選的複選框點選事件
        box_all_select.setOnClickListener(this);
    }
}

日誌管理器

package wanghuiqi.bawie.com.whq_shopper;

import java.io.IOException;

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

public class MyLog implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long t1 = System.nanoTime();
        System.out.println("request="+String.format("Sending request %s on %s%n%s",
                request.url(),chain.connection(),request.headers()));
        //拿到response物件
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();
        //得到請求網路
        System.out.println("response"+String.format("Received response for %s in %.1fms%n%s",
                response.request().url(),(t2-t1)/1e6d,response.headers()));
        return response;
    }
}

工具類

package wanghuiqi.bawie.com.whq_shopper.model;

import android.os.Handler;
import android.os.Looper;
import android.sax.StartElementListener;

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

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import wanghuiqi.bawie.com.whq_shopper.MyLog;

public class HttpUtils {

    private final Handler handler;
    private OkHttpClient httpClient;
    private static HttpUtils mHttpUtils;

    private HttpUtils() {
        //建立主執行緒的handler
        handler = new Handler(Looper.getMainLooper());
        //日誌攔截器
        MyLog myLog = new MyLog();
        httpClient = new OkHttpClient.Builder()
                .addInterceptor(myLog)
                .connectTimeout(5000, TimeUnit.MILLISECONDS)
                .readTimeout(5000, TimeUnit.MILLISECONDS)
                .writeTimeout(5000, TimeUnit.MILLISECONDS)
                .build();
    }

    //單例模式
    public static HttpUtils getInstance() {

        if (mHttpUtils == null) {
            synchronized (HttpUtils.class) {
                if (mHttpUtils == null) {
                    return mHttpUtils = new HttpUtils();
                }
            }
        }
        return mHttpUtils;
    }

    //建立介面
    public interface OKhttpInterface {
        void Failed(Exception e);

        void Success(String data);
    }

    public void doGet(String url, final OKhttpInterface moKhttpInterface) {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (moKhttpInterface != null) {
                    //切換到主執行緒
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            moKhttpInterface.Failed(e);
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (response != null && response.isSuccessful()) {
                        final String data = response.body().string();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (moKhttpInterface != null) {
                                    moKhttpInterface.Success(data);
                                    return;
                                }
                            }
                        });
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        });
    }


    public void doPost(String url, Map<String,String> map, final OKhttpInterface mOkhttp){
        //建立formBody的物件,把表單新增到formBody中
        FormBody.Builder builder = new FormBody.Builder();
        if (map!=null){
            for(String key:map.keySet()){
                builder.add(key,map.get(key));
            }
        }
        FormBody formBody=builder.build();
        //建立request物件
        Request request = new Request.Builder()
                .post(formBody)
                .url(url)
                .build();
        //建立Call物件
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (httpClient!=null){
                    //切換到主執行緒
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            mOkhttp.Failed(e);
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (response!=null&&response.isSuccessful()){
                        final String data = response.body().string();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (mOkhttp!=null){
                                    mOkhttp.Success(data);
                                    return;
                                }
                            }
                        });
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
                if (mOkhttp!=null){
                    mOkhttp.Failed(new Exception("網路異常"));
                }
            }
        });
    }
}

Presenter層 —ShopPresenter

package wanghuiqi.bawie.com.whq_shopper.presenter;

import com.google.gson.Gson;

import java.util.List;

import wanghuiqi.bawie.com.whq_shopper.bean.Shop;
import wanghuiqi.bawie.com.whq_shopper.model.HttpUtils;

public class ShopPresenter {
    public void ShopData(String url) {
        HttpUtils.getInstance().doGet(url, new HttpUtils.OKhttpInterface() {
            @Override
            public void Failed(Exception e) {
                mOnShopInterface.failed(e);
            }

            @Override
            public void Success(String data) {
                Shop shop = new Gson().fromJson(data, Shop.class);
                //得到具體資料的聚合
                List<Shop.DataBean> shopData = shop.getData();
                mOnShopInterface.success(shopData);
            }
        });
    }

    //建立介面
    public interface OnShopInterface {
        void failed(Exception e);

        void success(List<Shop.DataBean> shopData);
    }

    private OnShopInterface mOnShopInterface;

    public void setOnShopInterface(OnShopInterface onShopInterface) {
        mOnShopInterface = onShopInterface;
    }
}

shop bean類

package wanghuiqi.bawie.com.whq_shopper.bean;

import java.util.List;

public class Shop {

    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 {

        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 {
            

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