1. 程式人生 > >點餐(RecyclerView)

點餐(RecyclerView)

點餐(RecyclerView) 仿餓了麼點餐頁面

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

依賴:

implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.github.bumptech.glide:glide:4.8.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'

許可權:

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

一、Main

package gj.com.buycar.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import gj.com.buycar.R;
import gj.com.buycar.adapter.LeftAdapter;
import gj.com.buycar.adapter.RightAdapter;
import gj.com.buycar.bean.Goods;
import gj.com.buycar.bean.Result;
import gj.com.buycar.bean.Shop;
import gj.com.buycar.core.DataCall;
import gj.com.buycar.presenter.CartPresenter;

/**
 * 仿餓了麼點餐
 */
public class Frag03 extends Fragment implements DataCall<List<Shop>> {

    private RecyclerView mLeftRecycler;
    private RecyclerView mRightRecycler;
    private TextView mCount;
    private TextView mSumPrice;
    private LeftAdapter mLeftAdapter;
    private RightAdapter mRightAdapter;
    private CartPresenter cartPresenter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag03,container,false);
        //初始化元件
        mLeftRecycler = view.findViewById(R.id.left_recycler);
        mRightRecycler = view.findViewById(R.id.right_recycler);
        mCount = view.findViewById(R.id.goods_number);
        mSumPrice = view.findViewById(R.id.goods_sum_price);

        //設定recyclerview的佈局管理器
        mLeftRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        mRightRecycler.setLayoutManager(new LinearLayoutManager(getContext()));

        mLeftAdapter = new LeftAdapter();
        mRightAdapter = new RightAdapter();
        //設定條目點選時間
        mLeftAdapter.setOnItemClickListenter(new LeftAdapter.OnItemClickListenter() {
            @Override
            public void onItemClick(Shop shop) {
                //首先 先清空原來的右側資料
                mRightAdapter.clearList();//清空右側資料
                //在根據點選的店鋪條目重新新增資料到集合中
                mRightAdapter.addAll(shop.getList());//將店鋪的商品集合傳到右側介面卡
                //重新整理介面卡
                mRightAdapter.notifyDataSetChanged();
            }
        });
        mLeftRecycler.setAdapter(mLeftAdapter);//設定介面卡
        mRightAdapter.setOnNumListener(new RightAdapter.OnNumListener() {
            @Override
            public void onNum() {
                calculatePrice(mLeftAdapter.getList());//設定總價和總數量
            }
        });

        //設定右半邊介面卡
        mRightRecycler.setAdapter(mRightAdapter);
        //呼叫P層請求資料
        cartPresenter = new CartPresenter(this);
        cartPresenter.requestData();
        return view;
    }

    /**
     * @author dingtao
     * @date 2018/12/18 7:01 PM
     * 計算總價格
     */
    private void calculatePrice(List<Shop> shopList){
        double totalPrice=0;
        int totalNum = 0;
        for (int i = 0; i < shopList.size(); i++) {//迴圈的商家
            Shop shop = shopList.get(i);
            for (int j = 0; j < shop.getList().size(); j++) {
                Goods goods = shop.getList().get(j);
                //計算價格
                totalPrice = totalPrice + goods.getNum() * goods.getPrice();
                totalNum+=goods.getNum();//計數
            }
        }
        mSumPrice.setText("價格:"+totalPrice);
        mCount.setText(""+totalNum);
    }

    @Override
    public void success(List<Shop> data) {
        calculatePrice(data);//計算價格和數量
        mLeftAdapter.addAll(data);//左邊的新增型別

        //得到預設選中的shop,設定上顏色和背景
        Shop shop = data.get(1);
        shop.setTextColor(0xff000000);
        shop.setBackground(R.color.white);
        //根據左側商鋪給右側新增集合
        mRightAdapter.addAll(shop.getList());

        //重新整理介面卡
        mLeftAdapter.notifyDataSetChanged();
        mRightAdapter.notifyDataSetChanged();
    }

    @Override
    public void fail(Result result) {
        Toast.makeText(getContext(), result.getCode() + "   " +
                result.getMsg(), Toast.LENGTH_LONG).show();
    }
}

二、main層佈局

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


    <!--點餐系統-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/left_recycler"
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:background="@color/grayblack"></android.support.v7.widget.RecyclerView>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/right_recycler"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

    </LinearLayout>

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

        <ImageView
            android:id="@+id/shop_car_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:src="@drawable/gouwuc_r"/>

        <TextView
            android:id="@+id/goods_number"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:textSize="10sp"
            android:gravity="center"
            android:textColor="@color/white"
            android:layout_marginLeft="-10dp"
            android:background="@drawable/circle_red_bg"
            android:layout_alignParentTop="true"
            android:layout_toEndOf="@+id/shop_car_image"
            android:text="6"/>

        <TextView
            android:id="@+id/goods_sum_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="價格:¥1000"
            android:layout_marginLeft="20dp"
            android:layout_centerVertical="true"/>

    </RelativeLayout>

</LinearLayout>

三、Main佈局中用到的背景設定 circle_red_bg

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <!--圓形  加邊框-->
    <solid
        android:color="#D81B60"></solid>
</shape>

四、main中用到的左邊介面卡LeftAdapter

package gj.com.buycar.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

import gj.com.buycar.R;
import gj.com.buycar.bean.Shop;

/**
 * 左半邊的recyclerview
 */
public class LeftAdapter extends RecyclerView.Adapter<LeftAdapter.MyHolder> {

    //建立集合(店鋪)
    List<Shop> mList = new ArrayList<>();



    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(viewGroup.getContext(),
                R.layout.recycler_left_item,null);
        MyHolder myHolder = new MyHolder(view);
        return myHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder myHolder, int i) {
        //找資料
        final Shop shop = mList.get(i);
        myHolder.text.setText(shop.getSellerName());//設定店鋪名字
        //設定字型顏色和背景
        myHolder.text.setBackgroundResource(shop.getBackground());
        myHolder.text.setTextColor(shop.getTextColor());
        //設定條目點選事件
        myHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //設定字型的顏色
                for (int j = 0; j <mList.size() ; j++) {
                    mList.get(j).setTextColor(0xffffffff);//設定所有非點選條目的字型及背景
                    mList.get(j).setBackground(R.color.grayblack);
                }

                //點選的當前條目的背景及字型顏色
                shop.setBackground(R.color.white);
                shop.setTextColor(0xff000000);
                //重新整理介面卡
                notifyDataSetChanged();
                //點選完切換右邊的列表
                onItemClickListenter.onItemClick(shop);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public List<Shop> getList() {
        return mList;
    }

    public void addAll(List<Shop> data) {
        mList.addAll(data);
    }

    public class MyHolder extends RecyclerView.ViewHolder {

        private final TextView text;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            //初始化元件
            text = itemView.findViewById(R.id.left_text);
        }
    }

    private OnItemClickListenter onItemClickListenter;

    public void setOnItemClickListenter(OnItemClickListenter onItemClickListenter) {
        this.onItemClickListenter = onItemClickListenter;
    }

    //自定義點選的介面 設定set方法
    public interface OnItemClickListenter{
        void onItemClick(Shop shop);
    }

}

五、左介面卡用到的佈局檔案recycler_left_item

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

    <TextView
        android:id="@+id/left_text"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:textSize="16sp"
        android:gravity="center"
        android:textColor="@color/white"
        android:text="資料"/>

</LinearLayout>

六、main中用到的右邊介面卡RightAdapter

package gj.com.buycar.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

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

import gj.com.month_buycar.R;
import gj.com.buycar.bean.Goods;
import gj.com.buycar.core.GJApplication;
import gj.com.buycar.view.AddSubLayout;

/**
 * 右半邊的recyclerview
 */
public class RightAdapter extends RecyclerView.Adapter<RightAdapter.ChildHolder> {

    //建立集合(商品店鋪)
    List<Goods> mList = new ArrayList<>();


    @NonNull
    @Override
    public ChildHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(viewGroup.getContext(),R.layout.recycler_right_item,null);
        return new ChildHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ChildHolder childHolder, int i) {
        final Goods goods = mList.get(i);
        //獲得商品後 開始賦值
        childHolder.text.setText(goods.getTitle());
        childHolder.price.setText("單價:"+goods.getPrice());//單價

        //設定圖片
        String imageurl = "https" + goods.getImages().split("https")[1];
        Log.i("dt", "imageUrl: " + imageurl);
        imageurl = imageurl.substring(0, imageurl.lastIndexOf(".jpg") + ".jpg".length());
        Glide.with(GJApplication.getInstance()).
                load(imageurl).into(childHolder.image);//載入圖片

        childHolder.addSub.setCount(goods.getNum());//設定商品數量
        childHolder.addSub.setAddSubLinstener(new AddSubLayout.AddSubLinstener() {
            @Override
            public void addSub(int count) {
                goods.setNum(count);
                onNumListener.onNum();//計算價格
            }
        });
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public void clearList() {
        mList.clear();
    }

    public void addAll(List<Goods> list) {
        mList.addAll(list);
    }

    public class ChildHolder extends RecyclerView.ViewHolder {


        private final ImageView image;
        private final TextView text;
        private final TextView price;
        private final AddSubLayout addSub;

        public ChildHolder(@NonNull View itemView) {
            super(itemView);
            //初始化元件
            image = itemView.findViewById(R.id.image);
            text = itemView.findViewById(R.id.text);
            price = itemView.findViewById(R.id.text_price);
            addSub = itemView.findViewById(R.id.add_sub_layout);
        }
    }

    private OnNumListener onNumListener;

    public void setOnNumListener(OnNumListener onNumListener) {
        this.onNumListener = onNumListener;
    }

    public interface OnNumListener{
        void onNum();
    }
}

七、右介面卡用到的佈局檔案recycler_right_item

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:background="@drawable/search_edit_bg"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/image"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:minHeight="50dp"
        android:layout_alignParentLeft="true"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:id="@+id/text"
        android:layout_toRightOf="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:padding="10dp"
        android:text="aa"/>

    <TextView
        android:id="@+id/text_price"
        android:layout_toRightOf="@+id/image"
        android:layout_below="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="價格"
        android:padding="10dp"/>

    <!--呼叫自定義控制元件 + - -->
    <gj.com.month_buycar.view.AddSubLayout
        android:id="@+id/add_sub_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="50dp"
        android:layout_marginBottom="50dp"></gj.com.month_buycar.view.AddSubLayout>

</RelativeLayout>

八、右佈局檔案用到的背景search_edit_bg

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <!--設定圓角邊框及顏色-->
    <corners android:radius="20dp"/>

    <solid
        android:color="#d8d8d8"/>

</shape>

九、右佈局用到的AddSubLayout

package gj.com.buycar.view;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import gj.com.buycar.R;

public class AddSubLayout extends LinearLayout implements View.OnClickListener {

    private TextView mAddBtn;
    private TextView mSubBtn;
    private TextView mNumText;

    public AddSubLayout(Context context) {
        super(context);
        initView();
    }

    public AddSubLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public AddSubLayout(Context context,AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public AddSubLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView();
    }

    //建立佈局檢視
    private void initView() {
        //載入layout佈局,第三個引數ViewGroup一定寫成this
        View view = View.inflate(getContext(),
                R.layout.car_add_sub_layout,this);

        //初始化元件
        mAddBtn = view.findViewById(R.id.btn_add);
        mSubBtn = view.findViewById(R.id.btn_sub);
        mNumText = view.findViewById(R.id.text_number);

        //設定加減的點選事件
        mAddBtn.setOnClickListener(this);
        mSubBtn.setOnClickListener(this);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

        int width = r-1;//getWidth();
        int hright = b-t;//getHeight();
    }

    @Override
    public void onClick(View v) {
        //得到數量的值
        int number = Integer.parseInt(mNumText.getText().toString());

        switch (v.getId()){
            case R.id.btn_add:
                number++;
                mNumText.setText(number+"");//賦值
                break;

            case R.id.btn_sub:
                if(number==0){
                    Toast.makeText(getContext(),"數量不能小於0",Toast.LENGTH_LONG).show();
                    return;
                }

                number--;
                mNumText.setText(number+"");//賦值
                break;
        }
        if(addSubLinstener!=null){
            addSubLinstener.addSub(number);
        }
    }

    public void setCount(int count){
        mNumText.setText(count+"");
    }

    AddSubLinstener addSubLinstener;

    public void setAddSubLinstener(AddSubLinstener addSubLinstener) {
        this.addSubLinstener = addSubLinstener;
    }

    public  interface AddSubLinstener{
        void addSub(int count);
    }
}

十、AddSubLayout用到的佈局檔案car_add_sub_layout

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

    <!--加減框-->
    <TextView
        android:id="@+id/btn_add"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/car_btn_bg"
        android:focusable="false"
        android:textSize="16sp"
        android:gravity="center"
        android:text="+"/>

    <TextView
        android:id="@+id/text_number"
        android:layout_width="60dp"
        android:layout_height="30dp"
        android:gravity="center"
        android:textSize="14sp"
        android:text="10" />

    <TextView
        android:id="@+id/btn_sub"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:textSize="16sp"
        android:focusable="false"
        android:gravity="center"
        android:background="@drawable/car_btn_bg"
        android:text="-" />

</LinearLayout>

十一、car_add_sub_layout用到的背景檔案car_btn_bg

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <!--加減框的圓角邊框-->
    <corners
        android:radius="5dp"></corners>

    <!--邊框顏色-->
    <stroke
        android:color="@android:color/holo_red_dark"
        android:width="2dp"></stroke>

</shape>	

十二、介面

package gj.com.buycar.core;

import gj.com.buycar.bean.Result;

public interface DataCall<T> {
    void success(T data);
    void fail(Result result);
}

十三、右介面卡用到的GJApplication

package gj.com.buycar.core;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

public class GJApplication extends Application {

    private static GJApplication instance;
    private SharedPreferences mSharedPreferences;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mSharedPreferences = getSharedPreferences("application",
                Context.MODE_PRIVATE);

    }

    public static GJApplication getInstance() {
        return instance;
    }

    public SharedPreferences getShare() {
        return mSharedPreferences;
    }
}

十四、P層 CartPresenter

package gj.com.buycar.presenter;

import gj.com.buycar.bean.Result;
import gj.com.buycar.core.DataCall;
import gj.com.buycar.model.CartModel;

public class CartPresenter extends BasePresenter{
    public CartPresenter(DataCall dataCall) {
        super(dataCall);
    }

    @Override
    protected Result getData(Object... args) {
        //呼叫網路請求獲取資料M層
        Result result = CartModel.goodsList();
        return result;
    }
}

**十五、P層繼承的BasePresenter **

package gj.com.buycar.presenter;

import android.os.Handler;
import android.os.Message;

import gj.com.buycar.bean.Result;
import gj.com.buycar.core.DataCall;

public abstract class BasePresenter {

    //介面
    DataCall dataCall;

    public BasePresenter(DataCall dataCall) {
        this.dataCall = dataCall;
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Result result = (Result) msg.obj;
            //判斷是否成功
            if(result.getCode()==0){
                //將商鋪資訊傳過去
                dataCall.success(result.getData());
            }else{
                dataCall.fail(result);
            }
        }
    };

    //得到請求資料
    public void requestData(final Object...args){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = mHandler.obtainMessage();
                message.obj = getData(args);//定義一個抽象方法呼叫
                mHandler.sendMessage(message);
            }
        }).start();
    }

    protected abstract Result getData(Object...args);

    //避免記憶體溢位
    public void unBindCall(){
        this.dataCall = null;
    }
}

**十六、M層 **

package gj.com.buycar.model;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

import gj.com.buycar.bean.Result;
import gj.com.buycar.bean.Shop;
import gj.com.buycar.utils.HttpUtils;

public class CartModel {
    public static Result goodsList(){
        String resultString = HttpUtils.get("http://www.zhaoapi.cn/product/getCarts?uid=71");

       //try {

        //注意了
        Type type = new TypeToken<Result<List<Shop>>>(){}.getType();

        Result result = new Gson().fromJson(resultString, type);
        return result;
    /*} catch (Exception e) {

    }
    Result result = new Result();
        result.setCode(-1);
        result.setMsg("資料解析異常");
        return result;*/
    }
}

十七、OkHttp網路請求(包含get 和 post請求 可自行選擇)

package gj.com.buycar.model;

import android.util.Log;

import java.io.File;
import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtils {
    public static String get(String urlString){

        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder().url(urlString).get().build();

        try {
            Response response = okHttpClient.newCall(request).execute();
            String result = response.body().string();
            Log.i("dt","請求結果:"+result);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String postForm(String url,String[] name,String[] value){

        OkHttpClient okHttpClient = new OkHttpClient();

        FormBody.Builder formBuild = new FormBody.Builder();
        for (int i = 0; i < name.length; i++) {
            formBuild.add(name[i],value[i]);
        }

        Request request = new Request.Builder().url(url).post(formBuild.build()).build();

        try {
            Response response = okHttpClient.newCall(request).execute();

            String result = response.body().string();
            Log.i("dt",result);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String postFile(String url,String[] name,String[] value,String fileParamName,File file){

        OkHttpClient okHttpClient = new OkHttpClient();

        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if(file != null){
            // MediaType.parse() 裡面是上傳的檔案型別。
            RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
            String filename = file.getName();
            // 引數分別為: 檔案引數名 ,檔名稱 , RequestBody
            requestBody.addFormDataPart(fileParamName, "jpg", body);
        }
        if (name!=null) {
            for (int i = 0; i < name.length; i++) {
                requestBody.addFormDataPart(name[i], value[i]);
            }
        }

        Request request = new Request.Builder().url(url).post(requestBody.build()).build();

        try {
            Response response = okHttpClient.newCall(request).execute();
            if (response.code()==200) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String postJson(String url,String jsonString){

        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),jsonString);

        Request request = new Request.Builder().url(url).post(requestBody).build();

        try {
            Response response = okHttpClient.newCall(request).execute();

            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}

十八、用到的三個Bean類

①Result

package gj.com.month_buycar.bean;

import java.util.List;

public class Result<T> {

    private int code;
    private String msg;
    private T data;

    public String getMsg() {
        return msg;
    }

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

    public int getCode() {
        return code;
    }

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

    public T getData() {
        return data;
    }

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

②Shop

package gj.com.month_buycar.bean;

import java.util.List;

import gj.com.month_buycar.R;

public class Shop {

        /**
         * list : []
         * sellerName :
         * sellerid : 0
         */
        //商品的bean 多寫了三個東西 商品字型顏色 背景 選中狀態
        private List<Goods> list;
        private String sellerName;
        private String sellerid;
        int textColor = 0xffffffff;
        int background = R.color.grayblack;

        boolean check;

        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<Goods> getList() {
            return list;
        }

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

        public int getTextColor() {
            return textColor;
        }

        public void setTextColor(int textColor) {
            this.textColor = textColor;
        }

        public int getBackground() {
            return background;
        }

        public void setBackground(int background) {
            this.background = background;
        }

        public boolean isCheck() {
            return check;
        }

        public void setCheck(boolean check) {
            this.check = check;
        }
}

③Goods

package gj.com.month_buycar.bean;

import java.io.Serializable;

public class Goods implements Serializable {


    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 int count = 1;//多加了一個 商品的count

    public int getCount() {
        return count;
    }

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

    public double getBargainPrice() {
        return bargainPrice;
    }

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

    public String getCreatetime() {
        return createtime;
    }

    public void setCreatetime(String createtime) {
        this.createtime = createtime;
    }

    public String getDetailUrl() {
        return detailUrl;
    }

    public void setDetailUrl(String detailUrl) {
        this.detailUrl = detailUrl;
    }

    public String getImages() {
        return images;
    }

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

    public int getNum() {
        return num;
    }

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

    public int getPid() {
        return pid;
    }

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

    public double getPrice() {
        return price;
    }

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

    public int getPscid() {
        return pscid;
    }

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

    public int getSelected() {
        return selected;
    }

    public void setSelected(int selected) {
        this.selected = selected;
    }

    public int getSellerid() {
        return sellerid;
    }

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

    public String getSubhead() {
        return subhead;
    }

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

    public String getTitle() {
        return title;
    }

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