1. 程式人生 > >Android實現帶商家的二級購物車+MVP

Android實現帶商家的二級購物車+MVP

MainActivity程式碼

package com.bwie.shopcar.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bwie.shopcar.R;
import com.bwie.shopcar.adapter.ShopAdapter;
import com.bwie.shopcar.bean.ShopBean;
import com.bwie.shopcar.presenter.ShopPresenter;
import com.bwie.shopcar.view.ShopView;

public class MainActivity extends AppCompatActivity implements ShopView, View.OnClickListener {

    private RecyclerView mRecyclerview;
    private CheckBox mCb;
    private TextView mTotalprice;
    private TextView mTotalnum;
    private TextView mSubmit;
    private LinearLayout mPayLinearThird;
    private ShopPresenter presenter;
    private ShopAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        presenter = new ShopPresenter(this);
        presenter.getData();

        LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        adapter = new ShopAdapter(this);

        mRecyclerview.setLayoutManager(manager);
        mRecyclerview.setAdapter(adapter);

        adapter.setListener(new ShopAdapter.UpdateUiListener() {
            @Override
            public void setTotal(String total, String num, boolean allCheck) {
                mCb.setChecked(allCheck);
                mTotalnum.setText(num);
                mTotalprice.setText(total);
            }
        });

    }

    private void initView() {
        mRecyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        mCb = (CheckBox) findViewById(R.id.cb);
        mCb.setOnClickListener(this);
        mTotalprice = (TextView) findViewById(R.id.totalprice);
        mTotalnum = (TextView) findViewById(R.id.totalnum);
        mSubmit = (TextView) findViewById(R.id.submit);
        mPayLinearThird = (LinearLayout) findViewById(R.id.third_pay_linear);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cb:
                adapter.selectAll(mCb.isChecked());
                break;
            default:
                break;
        }
    }

    @Override
    public void success(ShopBean bean) {
        adapter.add(bean);
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detach();
    }
}
自定義控制元件的customview類
package com.bwie.shopcar.activity;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.bwie.shopcar.R;


public class CustomView extends LinearLayout {

    private Button reduce;
    private Button add;
    private EditText editeText;
    int mcount = 1;

    public CustomView(Context context) {
        super(context);
    }

    public CustomView(final Context context, AttributeSet attrs) {
        super(context, attrs);

        View view = View.inflate(context, R.layout.custom_view,null);
        reduce = view.findViewById(R.id.reduce);
        add = view.findViewById(R.id.add);
        editeText = view.findViewById(R.id.content);

        reduce.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String content = editeText.getText().toString().trim();
                    int count = Integer.valueOf(content);
                    if (count > 1){
                        mcount = count-1;
                        editeText.setText(mcount+"");
                        if (listener != null){
                            listener.click(mcount);
                        }
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });

        add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String content = editeText.getText().toString().trim();
                    int count = Integer.valueOf(content)+1;
                    mcount = count;
                    editeText.setText(mcount+"");
                    if (listener != null){
                        listener.click(mcount);
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });

        addView(view);
    }

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

    public void setEditText(int num){
        if(editeText != null){
            editeText.setText(num+"");
        }
    }

    ClickListener listener;
    public void setClickListener(ClickListener listener){
        this.listener = listener;
    }

    public interface ClickListener{
        public void click(int count);
    }

}

初始化imageloader的類
package com.bwie.shopcar.activity;

import android.app.Application;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

/**
 * Created by hp on 2017/11/22.
 */
public class IApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this).build();
        ImageLoader.getInstance().init(configuration);
    }
}

介面卡程式碼
package com.bwie.shopcar.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.bwie.shopcar.R;
import com.bwie.shopcar.activity.CustomView;
import com.bwie.shopcar.bean.ShopBean;
import com.nostra13.universalimageloader.core.ImageLoader;

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

/**
 * Created by hp on 2017/11/22.
 */
public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.MyHolder> {

    Context context;
    List<ShopBean.DataBean.ListBean> list;
    Map<String,String> map = new HashMap<>();

    public ShopAdapter(Context context){
        this.context = context;
    }

    public void add(ShopBean bean){
        if(this.list == null){
            this.list = new ArrayList<>();
        }
        for(ShopBean.DataBean shop : bean.getData()){
            map.put(shop.getSellerid(),shop.getSellerName());
            for(int i=0;i<shop.getList().size();i++){
                this.list.add(shop.getList().get(i));
            }
        }
        setFirst(this.list);
        notifyDataSetChanged();
    }

    public void setFirst(List<ShopBean.DataBean.ListBean> list){
        if(list.size()>0){
            list.get(0).setIsFirst(1);
            for(int i=1;i<list.size();i++){
                if(list.get(i).getSellerid() == list.get(i-1).getSellerid()){
                    list.get(i).setIsFirst(2);
                }else{
                    list.get(i).setIsFirst(1);
                }
            }
        }
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context,R.layout.activity_adapter,null);
        MyHolder holder = new MyHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(final MyHolder holder, final int position) {

        if(list.get(position).getIsFirst() == 1){
            holder.shop_checkbox.setVisibility(View.VISIBLE);
            holder.item_shopname.setVisibility(View.VISIBLE);
            holder.shop_checkbox.setChecked(list.get(position).isShopSelected());
            holder.item_shopname.setText(map.get(String.valueOf(list.get(position).getSellerid())));
        }else{
            holder.shop_checkbox.setVisibility(View.GONE);
            holder.item_shopname.setVisibility(View.GONE);
        }

        String[] url = list.get(position).getImages().split("\\|");
        ImageLoader.getInstance().displayImage(url[0],holder.item_pic);

        holder.item_name.setText(list.get(position).getTitle());
        holder.item_checkbox.setChecked(list.get(position).isItemSelected());
        holder.item_price.setText(list.get(position).getPrice()+"");
        holder.customView.setEditText(list.get(position).getNum());

        holder.shop_checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.get(position).setShopSelected(holder.shop_checkbox.isChecked());
                for (int i = 0;i<list.size();i++){
                    if (list.get(position).getSellerid() == list.get(i).getSellerid()){
                        list.get(i).setItemSelected(holder.shop_checkbox.isChecked());
                    }
                }
                notifyDataSetChanged();
                sum(list);
            }
        });

        holder.item_checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.get(position).setItemSelected(holder.item_checkbox.isChecked());
                for(int i=0;i<list.size();i++){
                    for(int j=0;j<list.size();j++){
                        if(list.get(i).getSellerid() == list.get(j).getSellerid() && !list.get(j).isItemSelected()){
                            list.get(i).setShopSelected(false);
                            break;
                        }else{
                            list.get(i).setShopSelected(true);
                        }
                    }
                }
                notifyDataSetChanged();
                sum(list);
            }
        });

        holder.item_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.remove(position);
                setFirst(list);
                notifyDataSetChanged();
                sum(list);
            }
        });

        holder.customView.setClickListener(new CustomView.ClickListener() {
            @Override
            public void click(int count) {
                list.get(position).setNum(count);
                notifyDataSetChanged();
                sum(list);
            }
        });

    }

    @Override
    public int getItemCount() {
        return list == null?0:list.size();
    }

    public void sum(List<ShopBean.DataBean.ListBean> list){
        int totalnum = 0;
        float totalprice = 0;
        boolean allCheck = true;
        for(int i =0;i<list.size();i++){
            if(list.get(i).isItemSelected()){
                totalnum += list.get(i).getNum();
                totalprice += list.get(i).getNum() * list.get(i).getPrice();
            }else{
                allCheck = false;
            }
        }
        listener.setTotal(totalprice+"",totalnum+"",allCheck);
    }

    public void selectAll(boolean check){
        for(int i =0;i<list.size();i++){
            list.get(i).setItemSelected(check);
            list.get(i).setShopSelected(check);
        }
        notifyDataSetChanged();
        sum(list);
    }

    class MyHolder extends RecyclerView.ViewHolder{

        CheckBox item_checkbox,shop_checkbox;
        ImageView item_pic,item_del;
        TextView item_name,item_price,item_shopname,item_size;
        CustomView customView;

        public MyHolder(View itemView) {
            super(itemView);
            item_checkbox = itemView.findViewById(R.id.item_checkbox);
            item_name = itemView.findViewById(R.id.item_name);
            item_pic = itemView.findViewById(R.id.item_pic);
            item_del = itemView.findViewById(R.id.item_del);
            item_price = itemView.findViewById(R.id.item_price);
            item_shopname = itemView.findViewById(R.id.item_shopname);
            item_size = itemView.findViewById(R.id.item_size);
            shop_checkbox = itemView.findViewById(R.id.shop_checkbox);
            customView = itemView.findViewById(R.id.customview);
        }
    }

    UpdateUiListener listener;
    public void setListener(UpdateUiListener listener){
        this.listener = listener;
    }

    public interface UpdateUiListener{
        public void setTotal(String total,String num,boolean allCheck);
    }


}

view層程式碼
package com.bwie.shopcar.view;

import com.bwie.shopcar.bean.ShopBean;

/**
 * Created by hp on 2017/11/22.
 */
public interface ShopView {
    public void success(ShopBean bean);
    public void failure(Exception e);
}
model層介面
package com.bwie.shopcar.model;

import com.bwie.shopcar.bean.ShopBean;

/**
 * Created by hp on 2017/11/22.
 */
public interface ShopModel {
    public void success(ShopBean bean);
    public void failure(Exception e);
}

model層程式碼
package com.bwie.shopcar.model;

import com.bwie.shopcar.bean.ShopBean;
import com.bwie.shopcar.okhttp.AbstractUiCallBack;
import com.bwie.shopcar.okhttp.OkhttpUtils;

/**
 * Created by hp on 2017/11/22.
 */
public class MyModel {

    public void getData(final ShopModel callback){
        OkhttpUtils.getInstance().asy(null, "http://120.27.23.105/product/getCarts?uid=100", new AbstractUiCallBack<ShopBean>() {

            @Override
            public void success(ShopBean bean) {
                callback.success(bean);
            }

            @Override
            public void failure(Exception e) {
                callback.failure(e);
            }
        });

    }
}

presenter類程式碼

package com.bwie.shopcar.presenter;

import com.bwie.shopcar.bean.ShopBean;
import com.bwie.shopcar.model.MyModel;
import com.bwie.shopcar.model.ShopModel;
import com.bwie.shopcar.view.ShopView;

/**
 * Created by hp on 2017/11/22.
 */
public class ShopPresenter {

    ShopView view;
    MyModel model;
    public ShopPresenter(ShopView view){
        this.view = view;
        this.model = new MyModel();
    }

    public void getData(){
        model.getData(new ShopModel() {
            @Override
            public void success(ShopBean bean) {
                if (view != null){
                    view.success(bean);
                }
            }

            @Override
            public void failure(Exception e) {
                if (view != null){
                    view.failure(e);
                }
            }
        });
    }

    public void detach(){
        view = null;
    }
}



okhttp二次封裝
package com.bwie.shopcar.okhttp;

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

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

/**
 * Created by muhanxi on 17/11/10.
 *
 *
 * Okhttp 單例 範型的封裝
 */

public class OkhttpUtils {

    private static OkhttpUtils okhttpUtils = null ;

    private OkhttpUtils(){

    }

    public static OkhttpUtils getInstance(){

        if(okhttpUtils == null){
            okhttpUtils = new OkhttpUtils();
            client = new OkHttpClient.Builder()
                    .readTimeout(20, TimeUnit.SECONDS)
                    .writeTimeout(20,TimeUnit.SECONDS)
                    .connectTimeout(20,TimeUnit.SECONDS)
                    //新增攔截器
                    .addInterceptor(new LoggingInterceptor())
                    .build();
        }
        return okhttpUtils ;

    }


    private static OkHttpClient client ;


    /**
     * 發起非同步請求
     * @param params
     * @param url
     * @param callBack
     */
    public void asy(Map<String,String> params,String url,AbstractUiCallBack callBack){
        Request request = null ;

        if(params != null){
            // post 請求
            FormBody.Builder builder = new FormBody.Builder() ;
            for(Map.Entry<String,String> entry : params.entrySet()){
                builder.add(entry.getKey(),entry.getValue());
            }
            FormBody body =  builder.build();
            request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
        } else {
            // get 請求
            request = new Request.Builder()
                    .url(url)
                    .build();
        }



        client.newCall(request).enqueue(callBack);

    }

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");


    public static void postFile(Map<String,String> map, String url, File file,AbstractUiCallBack callBack){

        String [] array =  file.getAbsolutePath().split("\\/");

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);

        for(Map.Entry<String,String> entry : map.entrySet()){
            builder.addFormDataPart(entry.getKey(),entry.getValue());
        }
        builder.addFormDataPart("imageFileName",array[array.length-1]);


        if(file.exists() && file.length() > 0){
            builder.addFormDataPart("image",array[array.length-1], RequestBody.create(MEDIA_TYPE_PNG,file));
        }
        MultipartBody body =  builder.build() ;

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(callBack);


    }

}
callback幫助類
package com.bwie.shopcar.okhttp;

import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by muhanxi on 17/11/10.
 *
 *  * Okhttp 單例 範型的封裝
 */

public  abstract  class AbstractUiCallBack<T> implements Callback {

    /**
     * 成功回撥
     * @param t
     */
    public abstract void success(T t);

    /**
     * 失敗回撥
     * @param e
     */
    public abstract void failure(Exception e);


    private Handler handler = null ;
    private Class clazz ;

    public AbstractUiCallBack(){
        handler = new Handler(Looper.getMainLooper());


        //  得到的是一個 AbstractUiCallBack<T> 的Type
       Type type =  getClass().getGenericSuperclass() ;

        // 得到的是T的實際Type
       Type [] arr =  ((ParameterizedType)type).getActualTypeArguments() ;

        clazz = (Class) arr[0] ;



    }




    @Override
    public void onFailure(Call call, IOException e) {

        failure(e);

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {


        try {
            String result = response.body().string();
            System.out.println("result = " + result);
            Gson gson = new Gson();

            final T t = (T) gson.fromJson(result,clazz);
package com.bwie.shopcar.okhttp;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 可以實現 新增公共請求引數
 */
public class LoggingInterceptor implements Interceptor {


  @Override public Response intercept(Chain chain) throws IOException {
    //首先取到Request
    Request request = chain.request();
    Response response = null;
    Request requestProcess = null ;
    if("GET".equals(request.method())){
      String url =  request.url().toString() + "&source=android";
      Request.Builder builder =  request.newBuilder() ;
      builder.get().url(url);
      requestProcess =  builder.build();
      response = chain.proceed(requestProcess);
    } else {
      FormBody.Builder builder = new FormBody.Builder() ;
      RequestBody requestBody =  request.body() ;
      if(requestBody instanceof FormBody){
        FormBody formBody = (FormBody)requestBody ;
        for (int i=0;i<formBody.size();i++){
          builder.add(formBody.encodedName(i),formBody.encodedValue(i));
        }
        builder.add("source","android");
      }
       requestProcess =  request.newBuilder().url(request.url().toString()).post(builder.build()).build() ;
      response = chain.proceed(requestProcess);
    }




    return response;
  }
}

handler.post(new Runnable() { @Override public void run() { success(t); } }); } catch (IOException e) { e.printStackTrace(); failure(e); } catch (JsonSyntaxException e) { e.printStackTrace(); failure(e); } }} 攔截器
package com.bwie.shopcar.okhttp;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 可以實現 新增公共請求引數
 */
public class LoggingInterceptor implements Interceptor {


  @Override public Response intercept(Chain chain) throws IOException {
    //首先取到Request
    Request request = chain.request();
    Response response = null;
    Request requestProcess = null ;
    if("GET".equals(request.method())){
      String url =  request.url().toString() + "&source=android";
      Request.Builder builder =  request.newBuilder() ;
      builder.get().url(url);
      requestProcess =  builder.build();
      response = chain.proceed(requestProcess);
    } else {
      FormBody.Builder builder = new FormBody.Builder() ;
      RequestBody requestBody =  request.body() ;
      if(requestBody instanceof FormBody){
        FormBody formBody = (FormBody)requestBody ;
        for (int i=0;i<formBody.size();i++){
          builder.add(formBody.encodedName(i),formBody.encodedValue(i));
        }
        builder.add("source","android");
      }
      requestProcess =  request.newBuilder().url(request.url().toString()).post(builder.build()).build() ;
      response = chain.proceed(requestProcess);
    }




    return response;
  }
}

bean程式碼
package com.bwie.shopcar.bean;

import java.util.List;

/**
 * Created by hp on 2017/11/22.
 */
public class ShopBean {
    /**
     * 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;
    }

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

        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;

            // 1 顯示商家  2 隱藏商家
            private int isFirst;

            // true 表示商家選中 false 相反
            private boolean shopSelected;

            // true 表示 當前商品是選中的 false 相反
            private boolean itemSelected;



            public double getBargainPrice() {
                return bargainPrice;
            }

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

            public String getCreatetime() {
                return createtime;
            }

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

            public String getDetailUrl() {
                return detailUrl;
            }

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

            public String getImages() {
                return images;
            }

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

            public int getNum() {
                return num;
            }

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

            public int getPid() {
                return pid;
            }

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

            public double getPrice() {
                return price;
            }

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

            public int getPscid() {
                return pscid;
            }

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

            public int getSelected() {
                return selected;
            }

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

            public int getSellerid() {
                return sellerid;
            }

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

            public String getSubhead() {
                return subhead;
            }

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

            public String getTitle() {
                return title;
            }

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


            public int getIsFirst() {
                return isFirst;
            }

            public void setIsFirst(int isFirst) {
                this.isFirst = isFirst;
            }

            public boolean isShopSelected() {
                return shopSelected;
            }

            public void setShopSelected(boolean shopSelected) {
                this.shopSelected = shopSelected;
            }

            public boolean isItemSelected() {
                return itemSelected;
            }

            public void setItemSelected(boolean itemSelected) {
                this.itemSelected = itemSelected;
            }
        }
    }
}

mainactivity佈局程式碼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activity.MainActivity">

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

    <LinearLayout
        android:layout_weight="0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="#FFFFFF"
        android:gravity="center_vertical"
        android:id="@+id/third_pay_linear"
        >

        <CheckBox
            android:id="@+id/cb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="全選"
            android:drawablePadding="5dp"
            />

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

            <TextView
                android:id="@+id/totalprice"
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:paddingLeft="10dp"
                android:paddingTop="10dp"
                android:text="總價:"
                android:textColor="#000"
                android:textSize="16sp"
                />

            <TextView
                android:textColor="#000"
                android:id="@+id/totalnum"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="10dp"
                android:text="共0件商品"
                android:textSize="14sp"
                android:paddingBottom="10dp"
                />

        </LinearLayout>

        <TextView
            android:id="@+id/submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="去結算"
            android:paddingLeft="30dp"
            android:paddingRight="30dp"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:textColor="#000000"
            android:layout_marginRight="10dp"
            />

    </LinearLayout>

</LinearLayout>

自定義控制元件佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/reduce"
        android:layout_width="10dp"
        android:layout_height="wrap_content"
        android:text="-"
        android:background="#fff"/>

    <EditText
        android:id="@+id/content"
        android:inputType="number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1" />

    <Button
        android:id="@+id/add"
        android:layout_width="10dp"
        android:layout_height="wrap_content"
        android:text="+"
        android:background="#fff"/>

</LinearLayout>

介面卡的佈局程式碼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/ll_shopcart_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <View
            android:layout_width="match_parent"
            android:layout_height="10dp"
            android:background="#f6f6f6"
            android:id="@+id/view"/>

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

            <!-- 商店checkbox -->

            <CheckBox
                android:id="@+id/shop_checkbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="15dp"
                android:paddingRight="15dp"
                android:paddingTop="10dp"
                android:paddingBottom="10dp"
                />

            <!-- 商店明晨 -->
            <TextView
                android:id="@+id/item_shopname"
                android:textColor="#000"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="寶兒家服裝"
                android:padding="10dp"
                android:drawablePadding="5dp"
                />

        </LinearLayout>

    </LinearLayout>

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


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

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#f6f6f6"
                />


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

                <!-- 商品 checkbox -->
                <CheckBox
                    android:id="@+id/item_checkbox"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="15dp"
                    />

                <!-- 商品圖片 -->
                <ImageView
                    android:id="@+id/item_pic"
                    android:layout_width="60dp"
                    android:layout_height="60dp"
                    android:layout_margin="10dp"
                    />

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

                    <TextView
                        android:id="@+id/item_price"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="¥185"
                        android:textColor="#e53e42"
                        android:textSize="14sp"
                        />

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        android:layout_marginBottom="5dp"
                        >

                        <TextView
                            android:textColor="#000"
                            android:id="@+id/item_name"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="顏色:黑色"
                            android:textSize="12sp"
                            />

                        <TextView
                            android:textColor="#000"
                            android:id="@+id/item_size"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="尺寸:XL"
                            android:textSize="12sp"
                            android:layout_marginLeft="10dp"
                            />

                    </LinearLayout>

                    <com.bwie.shopcar.activity.CustomView
                        android:id="@+id/customview"
                        android:layout_width="180dp"
                        android:layout_height="wrap_content" />

                </LinearLayout>

                <ImageView
                    android:id="@+id/item_del"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="20dp"
                    android:src="@drawable/shopcart_delete"
                    />

            </LinearLayout>



        </LinearLayout>

    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#f6f6f6"
        />


</LinearLayout>