mvp获取数据 完整的购物车 +自定义view的加减号

来源:互联网 发布:华为软件开发招聘 编辑:程序博客网 时间:2024/09/21 09:06

布局先行

   

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">   <android.support.v7.widget.RecyclerView        android:id="@+id/third_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/third_allselect"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="@dimen/margin_10dp"            android:drawableLeft="@drawable/shopcart_add_btn"            android:text="全选"            android:drawablePadding="@dimen/padding_5dp"            />        <LinearLayout            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:orientation="vertical"            >            <TextView                android:id="@+id/goodsPrice"                android:layout_width="200dp"                android:layout_height="wrap_content"                android:paddingLeft="@dimen/padding_10dp"                android:paddingTop="@dimen/padding_10dp"                android:text="总价:"                android:textColor="@color/cblack"                android:textSize="@dimen/common_font_size_16"                />            <TextView                android:textColor="@color/cblack"                android:id="@+id/goodsNum"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:paddingLeft="@dimen/padding_10dp"                android:text="共0件商品"                android:textSize="@dimen/common_font_size_14"                android:paddingBottom="@dimen/padding_10dp"                />        </LinearLayout>        <TextView            android:id="@+id/third_submit"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:background="@drawable/login_btn"            android:text="去结算"            android:paddingLeft="@dimen/margin_30dp"            android:paddingRight="@dimen/margin_30dp"            android:paddingTop="@dimen/padding_10dp"            android:paddingBottom="@dimen/padding_10dp"            android:textColor="#000000"            android:layout_marginRight="@dimen/margin_10dp"            />    </LinearLayout></LinearLayout>

//下面就是 Adapter 的天目布局了 会有一葛自定义的加入

 

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="@color/cwhite">    <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="@dimen/margin_10dp"            android:background="@color/background_color"            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:src="@drawable/shopcart_selected"                android:paddingLeft="@dimen/margin_15dp"                android:paddingRight="@dimen/margin_15dp"                android:paddingTop="@dimen/margin_10dp"                android:paddingBottom="@dimen/margin_10dp"                />            <!-- 商店明晨 -->            <TextView                android:textColor="@color/cblack"                android:id="@+id/tv_item_shopcart_shopname"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:drawableLeft="@drawable/shopcart_shop"                android:text="宝儿家服装"                android:padding="@dimen/padding_10dp"                android:drawablePadding="@dimen/padding_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="@dimen/margin_1dp"                android:background="@color/background_color"                />            <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:src="@drawable/shopcart_selected"                    android:padding="@dimen/margin_15dp"                    />                <!-- 商品图片 -->                <ImageView                    android:id="@+id/item_pic"                    android:layout_width="60dp"                    android:layout_height="60dp"                    android:layout_margin="@dimen/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="@color/main_red_text"                        android:textSize="@dimen/common_font_size_14"                        />                    <LinearLayout                        android:layout_width="wrap_content"                        android:layout_height="wrap_content"                        android:layout_marginTop="@dimen/margin_5dp"                        android:layout_marginBottom="@dimen/margin_5dp"                        >                        <TextView                            android:textColor="@color/cblack"                            android:id="@+id/item_name"                            android:layout_width="wrap_content"                            android:layout_height="wrap_content"                            android:text="颜色:黑色"                            android:textSize="@dimen/common_font_size_12"                            />                        <TextView                            android:textColor="@color/cblack"                            android:id="@+id/tv_item_shopcart_cloth_size"                            android:layout_width="wrap_content"                            android:layout_height="wrap_content"                            android:text="尺寸:XL"                            android:textSize="@dimen/common_font_size_12"                            android:layout_marginLeft="@dimen/margin_10dp"                            />                    </LinearLayout>                  <com.example.gq.shoucar.PlusView                        android:layout_width="150dp"                        android:layout_height="50dp"                        android:id="@+id/plus_view_id"                        />                </LinearLayout>                <View                    android:layout_width="@dimen/margin_1dp"                    android:layout_height="match_parent"                    android:layout_marginTop="@dimen/padding_10dp"                    android:layout_marginBottom="@dimen/padding_10dp"                    android:background="@color/splitline_color"                    />                <ImageView                    android:id="@+id/item_del"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:padding="@dimen/margin_20dp"                    android:src="@drawable/shopcart_delete"                    />            </LinearLayout>        </LinearLayout>    </LinearLayout>    <View        android:layout_width="match_parent"        android:layout_height="@dimen/margin_1dp"        android:background="@color/background_color"        /></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="horizontal"    >   <!--自定义view-->    <Button        android:layout_width="10dp"        android:layout_height="wrap_content"        android:id="@+id/revserse"        android:text="-"        android:background="#00FFFFFF"/>    <EditText        android:inputType="number"        android:text="1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/content"/>    <Button        android:background="#00FFFFFF"        android:text="+"        android:id="@+id/add"        android:layout_width="10dp"        android:layout_height="wrap_content"        /></LinearLayout>

 记得写自定义view的类

 

package com.example.gq.shoucar;import android.content.Context;import android.support.annotation.Nullable;import android.text.Editable;import android.text.TextWatcher;import android.util.AttributeSet;import android.view.LayoutInflater;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;/** * Created by muhanxi on 17/11/21. *//** * 购物车加减号 自定义View   继承linearlayoutx才能把布局控件写出来 */public class PlusView extends LinearLayout {    private EditText editText;    private Button revserse;    private Button add;    private int mCount = 1;    public PlusView(Context context) {        super(context);    }    public PlusView(Context context, @Nullable AttributeSet attrs) {        super(context, attrs);        View view = LayoutInflater.from(context).inflate(R.layout.plus_layout, null, false);        revserse = (Button) view.findViewById(R.id.revserse);  //减号        add = (Button) view.findViewById(R.id.add);  //加号        editText = (EditText) view.findViewById(R.id.content);  //中间的那个值        revserse.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View view) {                //减号                try {                    String content =  editText.getText().toString().trim() ;                    int count =  Integer.valueOf(content);                    if(count > 1){                        mCount = count-1;                        editText.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 =  editText.getText().toString().trim() ;                    int count =  Integer.valueOf(content)+1;                    mCount = count;                    editText.setText(count+"");                    if(listener != null){                        listener.click(count);                    }                } catch (NumberFormatException e) {                    e.printStackTrace();                }            }        });        editText.addTextChangedListener(new TextWatcher() {            @Override            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {            }            @Override            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {            }            @Override            public void afterTextChanged(Editable editable) {            }        });          addView(view);  //添加自定义view     }    public PlusView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    public void setEditText(int num){        if(editText != null){            editText.setText(num+"");        }    }    public ClickListener listener;    public void setListener(ClickListener listener){        this.listener = listener;    }    /**     * 加减号 点击事件     */    public interface ClickListener {        public void click(int count);    }}

// 开始写mvp

    接口 

package com.example.gq.shoucar.modle;import okhttp3.Callback;public interface MainModelCallBack {    public void success(Callback callback);}

  实现类

package com.example.gq.shoucar.modle;import com.example.gq.shoucar.util.OkHttp3Utils;import okhttp3.Callback;/** * Created by muhanxi on 17/11/21. */public class MainModel implements MainModelCallBack {    @Override  //数据在这里    public void success(Callback callback) {        OkHttp3Utils.doGet("http://120.27.23.105/product/getCarts?uid=100",callback);    }}


 p层

package com.example.gq.shoucar.presenter;import android.content.Context;import android.util.Log;import com.example.gq.shoucar.bean.ShopBean;import com.example.gq.shoucar.modle.MainModel;import com.example.gq.shoucar.util.OnUiCallback;import com.example.gq.shoucar.view.MainViewListener;import com.google.gson.Gson;import java.io.IOException;import okhttp3.Call;/** * Created by gq on 2017/11/21. */public class MainPresenter {  //实现 类    private  Context context;    private MainViewListener view;    private MainModel modle;  //获取数据    public MainPresenter(Context contexy, MainViewListener view) {        this.context=contexy;        this.view=view;        modle=new MainModel();     }      //乐意可以传值    public void aishasha() {
                //OnUiCallback是封装好的okhttp
modle.success(new OnUiCallback() { @Override public void onFailed(Call call, IOException e) { } @Override public void onSuccess(String result) { //是个json 传串 Gson gson = new Gson(); ShopBean shopBean = gson.fromJson(result, ShopBean.class); Log.i("json字符串",""+shopBean); view.success(shopBean);//跟新界面 } }); } public void asdf() //解决内存泄漏 对层和activity { view=null; }}

 mainActivity

package com.example.gq.shoucar;import android.content.Intent;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 com.example.gq.shoucar.bean.ShopBean;import com.example.gq.shoucar.presenter.MainPresenter;import com.example.gq.shoucar.view.MainViewListener;public class MainActivity extends AppCompatActivity implements MainViewListener {    MainPresenter presenter = new MainPresenter(this, this); //传视图到p层    private RecyclerView Recyclerview01;    private CheckBox third_allselect;    private TextView mTotalpriceThird;    private TextView mTotalnumThird;    private TextView mSubmitThird;    private LinearLayout mPayLinearThird;    private ShouAdapter adapter;    private RecyclerView mRecyclerviewThird;    private TextView goodsNum;    private TextView goodsPrice;    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();        presenter.aishasha();  //调数据        LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);        Recyclerview01.setLayoutManager(manager);        //传这个过去        adapter = new ShouAdapter(this);        Recyclerview01.setAdapter(adapter);  //设置适配器        adapter.setListener(new ShouAdapter.UpdateUiListener() {  //从适配器来的值            public void setTotal(String total, String num,boolean allCheck) {                third_allselect.setChecked(allCheck);                goodsNum.setText(num);                goodsPrice.setText(total);            }        });        adapter.setOnItemClickListener(new ShouAdapter.OnItemClickListener() {            //            public void onItemClick(View view, int position) {                Intent intent = new Intent(MainActivity.this,SecondActivity.class);                startActivity(intent);            }        });        third_allselect.setOnClickListener(new View.OnClickListener() {            public void onClick(View view) {                adapter.selectAll(third_allselect.isChecked());              }        });    }    private void initView() {        Recyclerview01 = (RecyclerView) findViewById(R.id.third_recyclerview);        third_allselect = (CheckBox) findViewById(R.id.third_allselect);        goodsNum = (TextView) findViewById(R.id.goodsNum);        goodsPrice = (TextView) findViewById(R.id.goodsPrice);        mSubmitThird = (TextView) findViewById(R.id.third_submit);        mPayLinearThird = (LinearLayout) findViewById(R.id.third_pay_linear);    }    @Override    public void success(ShopBean bean) { //更新UI的数据        //  mText01.setText(bean.getData().get(0).getList().get(0).getTitle());        //把这个bean传到adapter里面        adapter.add(bean);    }    //解决内存泄漏    // @Override    protected void onDestroy() {        super.onDestroy();        presenter.asdf();    }    //还有一个计算值得}
    展示数据的适配器

 

package com.example.gq.shoucar;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.example.gq.shoucar.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 gq on 2017/11/21. */    //public class ShouAdapter  extends RecyclerView.Adapter<ShouAdapter.IViewHolder> implements View.OnClickListener{      //传一个bean过来      Context context;    private OnItemClickListener mOnItemClickListener = null;    private List<ShopBean.DataBean.ListBean> list;        private Map<String,String> map = new HashMap<>();    public ShouAdapter( Context context) {  //传上下文过来          this.context=context;      }    /**     * 添加数据 并更新显示     * @param bean     */    public void add(ShopBean bean) {        if (this.list == null) {            this.list = new ArrayList<>();        }               // 遍历商家   bean.getData()这里面是外面对象里的 在里层是list        for (ShopBean.DataBean shop : bean.getData()) {              // 遍历商品              map.put(shop.getSellerid(),shop.getSellerName()); //键值对表id 对应商品名                for (int i = 0; i < shop.getList().size(); i++) {  //list集合内所有东西                    this.list.add(shop.getList().get(i));  //把所有商品都添加到集合里  只有商品                }         }                   setFirst(this.list);  //this.list               notifyDataSetChanged();   //添加进去数据后要更新UI    }    /**     * 设置数据源, 控制显示商家     * @param list     */    private void setFirst(List<ShopBean.DataBean.ListBean> list){        if(list.size() > 0){            list.get(0).setIsFirst(1);            for(int i=1;i<list.size();i++){   //每个商品背上都有商铺 第一个商品上面肯定要显示商家                //所以从每个商铺的第二个商品开始比 ,如果第三个商品和第二个商品的商铺id都一样  那第三个商品的一定不是 所以就隐藏                if(list.get(i).getSellerid() == list.get(i-1).getSellerid()){ //list.get(i).getSellerid(){是第三个商品}                    list.get(i).setIsFirst(2);//隐藏                  }else{                    list.get(i).setIsFirst(1);//显示                }            }        }    }   //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++         //选中    public ShouAdapter.IViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {        View view = View.inflate(context, R.layout.adapter_layout, null);        view.setOnClickListener((View.OnClickListener) this);        return new IViewHolder(view);           }    public void onBindViewHolder(final ShouAdapter.IViewHolder holder, final int position) {         //将position保存在itemView的Tag中,以便点击时进行获取              holder.itemView.setTag(position);  //条目点击事件        holder.shop_checkbox.setChecked(list.get(position).isShopSelected());  //给商铺赋初始值          holder.shop_checkbox.setOnClickListener(new View.OnClickListener() {              public void onClick(View view) {                  list.get(position).setShopSelected(holder.shop_checkbox.isChecked()); //获取选中或者非选中的状态 因为改变的是list集合的值                  // 所以要刷新                  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());                            //商铺选中之后就把这个商铺下面的所有和这个点击的商品上的商铺id都匹配一遍                          //然后把用一个商铺下面的id都放一块  商铺影响商品                      }                  }                    notifyDataSetChanged();                  //这里有个sum的加减                    sum(list);              }            });        holder.item_checkbox.setChecked(list.get(position).isItemSelected()); //初始值        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()){                            //if(list.get(i).getSellerid() == list.get(j).getSellerid()  判断商品是否是一个商铺的                            //list.get(j).isItemSelected() //true和false                            //同一个商铺里面只要有一个商屏是未选中 就给商铺赋值一个非 斌退出循环                            list.get(i).setShopSelected(false);  //i是遍历的所有的商品                            break;                        }else {                            list.get(i).setShopSelected(true);                        }                    }                 }                  notifyDataSetChanged();                //这里有个sum的加减 );                  sum(list);            }        });     ///////////////////////////////////////////////////////////////////////////////////            holder.item_del.setOnClickListener(new View.OnClickListener() {                public void onClick(View view){                       list.remove(position);                           //也要跟新一下setisFice()//删除第二个条目                           setFirst(list);                       sum(list);                      notifyDataSetChanged(); //刷新数据                }            });        // -------------------------------------------------------------------------------        // 显示商品图片          if(list.get(position).getIsFirst() == 1){            //显示商家            holder.shop_checkbox.setVisibility(View.VISIBLE);            holder.tvItemShopcartShopname.setVisibility(View.VISIBLE);              holder.shop_checkbox.setChecked(list.get(position).isShopSelected()); //商家选中//            显示商家的名称//            list.get(position).getSellerid() 取到商家的id//            map.get()取到 商家的名称      还需要一个map集合            holder.tvItemShopcartShopname.setText(map.get(String.valueOf(list.get(position).getSellerid())));        } else {            holder.shop_checkbox.setVisibility(View.GONE);            holder.tvItemShopcartShopname.setVisibility(View.GONE);        }        ////////////////////////////展示////////////////////////////////////////////////////        String[] url = list.get(position).getImages().split("\\|"); //分隔符        ImageLoader.getInstance().displayImage(url[0],holder.imageView);          holder.name.setText(list.get(position).getTitle());          holder.price.setText(list.get(position).getPrice()+"");          holder.plusViewId.setEditText(list.get(position).getNum()); //显示数量       //--------------------------商家显示隐藏 ------------------------------------------------        //加减号        holder.plusViewId.setListener(new PlusView.ClickListener() {            public void click(int count) {                list.get(position).setNum(count);                notifyDataSetChanged();                sum(list);            }        });    }    public int getItemCount() {        return list == null ? 0 : list.size();    }    /**     * 计算总价     * @param list     */    private void sum(List<ShopBean.DataBean.ListBean> list){        int totalNum = 0 ;        float totalMoney =  0.0f;        boolean allCheck =true;        for(int i=0;i<list.size();i++){            if(list.get(i).isItemSelected()){                totalNum += list.get(i).getNum() ;                totalMoney += list.get(i).getNum() * list.get(i).getPrice();            }else {                allCheck = false;            }        }        listener.setTotal(totalMoney+"",totalNum+"",allCheck);          //设置值给 main    }    //点击条目的方法     public void onClick(View v) {        if (mOnItemClickListener != null) {            //注意这里使用getTag方法获取position            mOnItemClickListener.onItemClick(v,(int)v.getTag());        }    }    public void selectAll(boolean checked) {        for(int i=0;i<list.size();i++){            list.get(i).setShopSelected(checked); //所有商铺的选中状态            //所有上平的选中状态            list.get(i).setItemSelected(checked);        }        sum(list);        notifyDataSetChanged();    }    static class IViewHolder extends RecyclerView.ViewHolder{          private final ImageView imageView;          private final TextView price;          private final TextView name;          private final CheckBox shop_checkbox; //商家的多选框          private final TextView tvItemShopcartShopname;//购物车商家名          private final CheckBox item_checkbox;          private final ImageView item_del;        private final PlusView plusViewId;        public IViewHolder(View itemView) {              super(itemView);              name = (TextView) itemView.findViewById(R.id.item_name);              price = (TextView) itemView.findViewById(R.id.item_price);              imageView = (ImageView) itemView.findViewById(R.id.item_pic);              shop_checkbox = (CheckBox) itemView.findViewById(R.id.shop_checkbox);              item_checkbox = (CheckBox) itemView.findViewById(R.id.item_checkbox); //条目商品的id              tvItemShopcartShopname = (TextView) itemView.findViewById(R.id.tv_item_shopcart_shopname);//商家展示              item_del = (ImageView) itemView.findViewById(R.id.item_del);  //删除按钮的              plusViewId = (PlusView) itemView.findViewById(R.id.plus_view_id);          }      }//控件    public void setOnItemClickListener(OnItemClickListener listener) {        this.mOnItemClickListener = listener;    }     public static interface OnItemClickListener {        void onItemClick(View view , int position);     }    public UpdateUiListener listener;    public void setListener(UpdateUiListener listener){        this.listener = listener;    }    interface UpdateUiListener {// 往这里添加值        public void setTotal(String total,String num,boolean allCheck);    }}

//最后还需要导入工具类  okhttp的封装

 

package com.example.gq.shoucar.util;import android.util.Log;import java.io.File;import java.io.IOException;import java.util.Map;import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;/** * 1. 类的用途 * 2. @author  *  */public class OkHttp3Utils {    private static OkHttpClient okHttpClient = null;    public OkHttp3Utils() {    }    private static OkHttpClient getOkHttpClient() {        synchronized (OkHttp3Utils.class) {            if (okHttpClient == null) {                okHttpClient = new OkHttpClient();            }        }        return okHttpClient;    }    //上传文件    public static void loadFile(String url, File file,String fileName){        OkHttpClient okHttpClient = getOkHttpClient();        //设置文件类型        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"),file);        //设置请求体        RequestBody body = new MultipartBody.Builder()                .setType(MultipartBody.FORM)                .addFormDataPart("image",fileName,requestBody)                .build();        //请求方式        Request request = new Request.Builder().url(url).post(body).build();        okHttpClient.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {            }            @Override            public void onResponse(Call call, Response response) throws IOException {                Log.i("成功","成功");            }        });    }    /**     * 1.接口地址     * 2.接口回调     */    public static void doGet(String url,Callback callback){        OkHttpClient okHttpClient = getOkHttpClient();        Request request = new Request.Builder().url(url).build();        okHttpClient.newCall(request).enqueue(callback);    }    /**     * 1.地址     * 2.接口回调     * 3.请求体     */    public static void doPost(String url, Map<String,String> map,Callback callback){        OkHttpClient okHttpClient = getOkHttpClient();        FormBody.Builder builder = new FormBody.Builder();        //遍历map集合   设置请求体        for (String mapKey : map.keySet()){           builder.add(mapKey,map.get(mapKey));        }        //设置请求方式        Request request = new Request.Builder().url(url).post(builder.build()).build();        //执行请求方式    接口回调        okHttpClient.newCall(request).enqueue(callback);    }    /**     *1.下载地址     */    public static void doDown(String url,Callback callback){        OkHttpClient okHttpClient = getOkHttpClient();        Request build = new Request.Builder().url(url).build();        okHttpClient.newCall(build).enqueue(callback);    }}

2.个

package com.example.gq.shoucar.util;import android.os.Handler;import okhttp3.Callback;import okhttp3.OkHttpClient;import okhttp3.Request;/** * Created by lenovo on 2017/10/12. */public class OkHttpUtils {    private Handler handler=new Handler();    public Handler getHandler(){        return handler;    }    //单例    private static OkHttpUtils okHttpUtils=new OkHttpUtils();    private OkHttpUtils(){};    public static OkHttpUtils getInstance(){        return okHttpUtils;    }    private OkHttpClient client;    private void initOkHttpClient(){        if (client==null){            client=new OkHttpClient.Builder().build();        }    }    //公用的get请求方法  完成的功能不确定    public void doGet(String url, Callback callback){        initOkHttpClient();        Request request=new Request.Builder().url(url).build();        client.newCall(request).enqueue(callback);    }}

3.

package com.example.gq.shoucar.util;import android.os.Handler;import java.io.IOException;import okhttp3.Call;import okhttp3.Callback;import okhttp3.Response;/** * Created by lenovo on 2017/10/12. */public abstract class OnUiCallback implements Callback {    private Handler handler=OkHttpUtils.getInstance().getHandler();    public abstract void onFailed(Call call,IOException e);    public abstract void onSuccess(String result);    @Override    public void onFailure(final Call call, final IOException e) {        //该方法就是把  线程post到handler所在的线程        handler.post(new Runnable() {            @Override            public void run() {//                e.getMessage()                onFailed(call,e);            }        });    }    @Override    public void onResponse(Call call, Response response) throws IOException {        final String result=response.body().string();        handler.post(new Runnable() {            @Override            public void run() {                onSuccess(result);            }        });    }}

适配器里 imageloader的 初始值

package com.example.gq.shoucar.bean;import android.app.Application;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;/** * Created by muhanxi on 17/11/21. */public class IApplication extends Application {    @Override    public void onCreate() {        super.onCreate();        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this).build();        ImageLoader.getInstance().init(configuration);    }}

  

  Bean

package com.example.gq.shoucar.bean;import java.util.List;/** * Created by gq on 2017/11/21. */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 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;            }            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;            }        }    }}

//build 需要的依赖

compile files('libs/okio-1.13.0.jar')compile files('libs/okhttp-3.9.0.jar')compile files('libs/gson-2.2.4.jar')compile files('libs/glide-3.7.0.jar')compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'compile 'com.android.support:recyclerview-v7:25.3.1'compile 'com.jcodecraeer:xrecyclerview:1.3.2'

   


清单文件需要配置

<uses-permission android:name="android.permission.INTERNET" /><application    android:name=".bean.IApplication"