实现线性和网格可以相互切换

//MainActivity页面


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;


import com.example.administrator.zuoyehehe.adapter.MyAdapter;
import com.example.administrator.zuoyehehe.R;
import com.example.administrator.zuoyehehe.presenter.ShopSearchPresenter;
import com.example.administrator.zuoyehehe.bean.GoodsBean;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;


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


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


    private ImageView cutImg;
    private Button btnSearch;
    private List<GoodsBean.DataBean> list = new ArrayList<>();
    private XRecyclerView xR;
    private EditText editKey;
    private int flag = 1;
    private MyAdapter myAdapter;
    private int i = 1;
    private String string = "手机";
    private String name;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //加载控件
        initView();
        getData("手机", "1");


        //设置可上拉
        xR.setPullRefreshEnabled(true);
        xR.setLoadingMoreEnabled(true);
        //设置上拉下拉样式
        xR.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xR.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);


        clickListener();


        xR.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                i = 1;
                list.clear();
                getData(string, "" + i);
                xR.refreshComplete();
            }


            @Override
            public void onLoadMore() {
                i++;
                getData(string, "" + i);
                xR.loadMoreComplete();
            }
        });




    }


    public void getData(String key, String page) {
        ShopSearchPresenter shopSearchPresenter = new ShopSearchPresenter(this, this);
        shopSearchPresenter.getGoodsData("http://120.27.23.105/product/searchProducts", key, page);
    }


    private void clickListener() {
        cutImg.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
    }


    private void initView() {
        cutImg = (ImageView) findViewById(R.id.cutImg);
        btnSearch = (Button) findViewById(R.id.btnSearch);
        xR = (XRecyclerView) findViewById(R.id.xrecyclerview);
        editKey = (EditText) findViewById(R.id.editKey);
    }


    @Override
    public void getSuccess(Object o) {
        GoodsBean o1 = (GoodsBean) o;
        List<GoodsBean.DataBean> data = (List<GoodsBean.DataBean>) o1.getData();
        list.addAll(data);
        setMyAdapter(flag);
    }


    @Override
    public void getFailed(Exception e) {


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cutImg:
                if (flag == 1) {
                    cutImg.setImageResource(R.drawable.kind_grid);
                    flag = 2;
                } else {
                    cutImg.setImageResource(R.drawable.kind_grid);
                    flag = 1;
                }
                setMyAdapter(flag);
                break;
            case R.id.btnSearch:
                list.clear();
                name = editKey.getText().toString();
                string = name;
                getData(string, "1");
                break;
        }
    }


    public void setMyAdapter(int f) {
        if (f == 1) {
            // 线性布局管理器   VERTICAL默认样式/竖向显示       第三个参数是数据是否到过来显示
            LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            //添加布局管理器
            xR.setLayoutManager(manager);
            myAdapter = new MyAdapter(list, this, f);
            xR.setAdapter(myAdapter);
        } else if (f == 2) {
            // 线性布局管理器   VERTICAL默认样式/竖向显示       第三个参数是数据是否到过来显示
            GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
            //添加布局管理器
            xR.setLayoutManager(gridLayoutManager);
            myAdapter = new MyAdapter(list, this, f);
            xR.setAdapter(myAdapter);
        }
    }

}


//创建适配器

import android.content.Context;
import android.graphics.Paint;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.example.administrator.zuoyehehe.R;
import com.example.administrator.zuoyehehe.bean.GoodsBean;


import java.util.List;


/**
 * Created by Administrator on 2018/4/18.
 */


public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private List<GoodsBean.DataBean> list;
    private Context context;
    private int flag = 1;
    private View inflate;


    public MyAdapter(List<GoodsBean.DataBean> list, Context context, int flag) {
        this.list = list;
        this.context = context;
        this.flag = flag;
    }


    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (flag == 1) {
            inflate = LayoutInflater.from(context).inflate(R.layout.lv_icon, parent, false);
        } else if (flag == 2) {
            inflate = LayoutInflater.from(context).inflate(R.layout.grid_icon, parent, false);
        }


        MyViewHolder myViewHolder = new MyViewHolder(inflate);


        return myViewHolder;
    }


    @Override
    public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {


        String images = list.get(position).getImages();
        String[] split = images.split("\\|");
        Glide.with(context).load(split[0]).into(holder.icon);
        holder.title.setText(list.get(position).getTitle());
        holder.bargainPrice.setText("折扣价:" + list.get(position).getBargainPrice() + "");
        holder.price.setText("原价:" + list.get(position).getPrice());
        holder.price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);


    }


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


    class MyViewHolder extends RecyclerView.ViewHolder {


        private ImageView icon;
        private TextView title;
        private TextView bargainPrice;
        private TextView price;


        public MyViewHolder(View itemView) {
            super(itemView);


            icon = (ImageView) itemView.findViewById(R.id.GoodsIcon);
            title = (TextView) itemView.findViewById(R.id.title);
            bargainPrice = (TextView) itemView.findViewById(R.id.bargainPrice);
            price = (TextView) itemView.findViewById(R.id.price);


        }
    }


}

//bean包

import java.util.List;


/**
 * Created by Administrator on 2018/4/18.
 */


public class GoodsBean {


    /**
     * msg : 查询成功
     * code : 0
     * data : [{"bargainPrice":3455,"createtime":"2017-10-03T23:53:28","detailUrl":"https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","itemtype":0,"pid":54,"price":888,"pscid":39,"salenum":7575,"sellerid":10,"subhead":"【现货新品抢购】全面屏2.0震撼来袭,骁龙835处理器,四曲面陶瓷机","title":"小米(MI) 小米MIX2 手机 黑色 全网通 (6GB+64GB)【标配版】"},{"bargainPrice":99,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/4345173.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6037/35/2944615848/95178/6cd6cff0/594a3a10Na4ec7f39.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6607/258/1025744923/75738/da120a2d/594a3a12Ne3e6bc56.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6370/292/1057025420/64655/f87644e3/594a3a12N5b900606.jpg!q70.jpg","itemtype":1,"pid":45,"price":2999,"pscid":39,"salenum":4666,"sellerid":1,"subhead":"高清双摄,就是清晰!2000+1600万高清摄像头,6GB大内存+高通骁龙835处理器,性能怪兽!","title":"一加手机5 (A5000) 6GB+64GB 月岩灰 全网通 双卡双待 移动联通电信4G手机"},{"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","itemtype":0,"pid":46,"price":234,"pscid":39,"salenum":868,"sellerid":2,"subhead":"【iPhone新品上市】新一代iPhone,让智能看起来更不一样","title":"Apple iPhone 8 Plus (A1864) 64GB 金色 移动联通电信4G手机"},{"bargainPrice":3455,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","itemtype":1,"pid":55,"price":5999,"pscid":39,"salenum":788,"sellerid":11,"subhead":"【现货新品抢购】全面屏2.0震撼来袭,骁龙835处理器,四曲面陶瓷机","title":"小米(MI) 小米MIX2 手机 黑色 全网通 (6GB+64GB)【标配版】"},{"bargainPrice":1599,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/1993026402.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t5863/302/8961270302/97126/41feade1/5981c81cNc1b1fbef.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7003/250/1488538438/195825/53bf31ba/5981c57eN51e95176.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5665/100/8954482513/43454/418611a9/5981c57eNd5fc97ba.jpg!q70.jpg","itemtype":2,"pid":47,"price":111,"pscid":39,"salenum":757,"sellerid":3,"subhead":"碳黑色 32GB 全网通 官方标配   1件","title":"锤子 坚果Pro 特别版 巧克力色 酒红色 全网通 移动联通电信4G手机 双卡双待 碳黑色 32GB 全网通"},{"bargainPrice":3455,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","itemtype":1,"pid":56,"price":99,"pscid":39,"salenum":757,"sellerid":12,"subhead":"【现货新品抢购】全面屏2.0震撼来袭,骁龙835处理器,四曲面陶瓷机","title":"小米(MI) 小米MIX2 手机 黑色 全网通 (6GB+64GB)【标配版】"},{"bargainPrice":3455,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","itemtype":1,"pid":48,"price":222,"pscid":39,"salenum":656,"sellerid":4,"subhead":"【现货新品抢购】全面屏2.0震撼来袭,骁龙835处理器,四曲面陶瓷机","title":"小米(MI) 小米MIX2 手机 黑色 全网通 (6GB+64GB)【标配版】"},{"bargainPrice":3455,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","itemtype":1,"pid":51,"price":555,"pscid":39,"salenum":424,"sellerid":7,"subhead":"【现货新品抢购】全面屏2.0震撼来袭,骁龙835处理器,四曲面陶瓷机","title":"小米(MI) 小米MIX2 手机 黑色 全网通 (6GB+64GB)【标配版】"},{"bargainPrice":3455,"createtime":"2017-10-03T23:53:28","detailUrl":"https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg","itemtype":0,"pid":52,"price":666,"pscid":39,"salenum":212,"sellerid":8,"subhead":"【现货新品抢购】全面屏2.0震撼来袭,骁龙835处理器,四曲面陶瓷机","title":"小米(MI) 小米MIX2 手机 黑色 全网通 (6GB+64GB)【标配版】"},{"bargainPrice":1999,"createtime":"2017-10-10T16:09:02","detailUrl":"https://item.m.jd.com/product/5025971.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t7210/232/3738666823/232298/9004583e/59c3a9a7N8de42e15.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8356/82/2107423621/109733/c019b8c6/59c3a9a6Ne9a4bdd7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t10219/74/25356012/171379/7d55e296/59c3a9a8N82fa6e02.jpg!q70.jpg","itemtype":0,"pid":49,"price":333,"pscid":39,"salenum":123,"sellerid":5,"subhead":"vivo X20 带你开启全面屏时代!逆光也清晰,照亮你的美!","title":"vivo X20 全面屏手机 全网通 4GB+64GB 金色 移动联通电信4G手机 双卡双待"}]
     * page : 1
     */


    private String msg;
    private String code;
    private String page;
    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 String getPage() {
        return page;
    }


    public void setPage(String page) {
        this.page = page;
    }


    public List<DataBean> getData() {
        return data;
    }


    public void setData(List<DataBean> data) {
        this.data = data;
    }


    public static class DataBean {
        /**
         * bargainPrice : 3455
         * createtime : 2017-10-03T23:53:28
         * detailUrl : https://item.m.jd.com/product/12224420750.html?utm_source=androidapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=QQfriends
         * images : https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t9106/106/1785172479/537280/253bc0ab/59bf78a7N057e5ff7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8461/5/1492479653/68388/7255e013/59ba5e84N91091843.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8803/356/1478945529/489755/2a163ace/59ba5e84N7bb9a666.jpg!q70.jpg
         * itemtype : 0
         * pid : 54
         * price : 888
         * pscid : 39
         * salenum : 7575
         * sellerid : 10
         * subhead : 【现货新品抢购】全面屏2.0震撼来袭,骁龙835处理器,四曲面陶瓷机
         * title : 小米(MI) 小米MIX2 手机 黑色 全网通 (6GB+64GB)【标配版】
         */


        private int bargainPrice;
        private String createtime;
        private String detailUrl;
        private String images;
        private int itemtype;
        private int pid;
        private int price;
        private int pscid;
        private int salenum;
        private int sellerid;
        private String subhead;
        private String title;


        public int getBargainPrice() {
            return bargainPrice;
        }


        public void setBargainPrice(int 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 getItemtype() {
            return itemtype;
        }


        public void setItemtype(int itemtype) {
            this.itemtype = itemtype;
        }


        public int getPid() {
            return pid;
        }


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


        public int getPrice() {
            return price;
        }


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


        public int getPscid() {
            return pscid;
        }


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


        public int getSalenum() {
            return salenum;
        }


        public void setSalenum(int salenum) {
            this.salenum = salenum;
        }


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

}


// ShopSearchModle 类

import com.example.administrator.zuoyehehe.net.CallBack;
import com.example.administrator.zuoyehehe.bean.GoodsBean;
import com.example.administrator.zuoyehehe.net.HttpUtils;
import com.example.administrator.zuoyehehe.presenter.ShopSearchPresenterAPI;


import java.util.Map;


/**
 * Created by Administrator on 2018/4/18.
 */


public class ShopSearchModle {
    public void getData(String url, Map<String, String> map, final ShopSearchPresenterAPI shopSearchPresenterAPI) {
        HttpUtils.getInstance().get(url, map, new CallBack() {
            @Override
            public void onSuccess(Object o) {
                shopSearchPresenterAPI.success(o);
            }


            @Override
            public void onFailed(Exception e) {
                shopSearchPresenterAPI.failed(e);
            }
        }, GoodsBean.class);
    }

}


//CallBack 接口类

public interface CallBack {
    void onSuccess(Object o);


    void onFailed(Exception e);

}


//解析工具包


import android.os.Handler;


import com.google.gson.Gson;


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


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by Administrator on 2018/4/18.
 */


public class HttpUtils {
    private static volatile HttpUtils instance;


    private static Handler handler = new Handler();


    private HttpUtils() {


    }


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


    //get请求
    public void get(String url, Map<String, String> map, final CallBack callBack, final Class c) {
        //对url和参数做拼接处理
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(url);
        //判断是否存在?   if中是存在
        if (stringBuffer.indexOf("?") != -1) {
            //判断?是否在最后一位    if中是不在最后一位
            if (stringBuffer.indexOf("?") != stringBuffer.length() - 1) {
                stringBuffer.append("&");
            }
        } else {
            stringBuffer.append("?");
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            stringBuffer.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }
        //判断是否存在&   if中是存在
        if (stringBuffer.indexOf("&") != -1) {
            stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("&"));
        }




        //1:创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Logger()).build();
        //2:创建Request对象
        final Request request = new Request.Builder()
                .get()
                .url(stringBuffer.toString())
                .build();
        //3:创建Call对象
        Call call = okHttpClient.newCall(request);
        //4:请求网络
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailed(e);
                    }
                });
            }


            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                //拿到数据解析
                final Object o = new Gson().fromJson(result, c);
                //当前是在子线程,回到主线程中
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //回调
                        callBack.onSuccess(o);
                    }
                });
            }
        });


    }


    //post请求
    public void post(String url, Map<String, String> map, final CallBack callBack, final Class c) {
        //1:创建OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //2:提供post请求需要的body对象
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        FormBody body = builder.build();
        //3:创建Request对象
        final Request request = new Request.Builder()
                .post(body)
                .url(url)
                .build();
        //4:创建Call对象
        Call call = okHttpClient.newCall(request);
        //5:请求网络
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailed(e);
                    }
                });
            }


            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                //拿到数据解析
                final Object o = new Gson().fromJson(result, c);
                //当前是在子线程,回到主线程中
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //回调
                        callBack.onSuccess(o);
                    }
                });
            }
        });
    }


}



//Logger类

import java.io.IOException;


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


/**
 * Created by Administrator on 2018/4/18.
 */


public class Logger implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        HttpUrl url = original.url().newBuilder()
                .addQueryParameter("source", "android")
                .build();
        //添加请求头
        Request request = original.newBuilder()
                .url(url)
                .build();
        return chain.proceed(request);
    }

}


//ShopSearchPresenter方法

import android.content.Context;


import com.example.administrator.zuoyehehe.model.ShopSearchModle;
import com.example.administrator.zuoyehehe.view.ShopSearchViewAPI;


import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2018/4/18.
 */


public class ShopSearchPresenter {
    private ShopSearchViewAPI shopSearchViewAPI;
    private Context context;
    private final ShopSearchModle shopSearchModle;


    public ShopSearchPresenter(ShopSearchViewAPI shopSearchViewAPI, Context context) {
        this.shopSearchViewAPI = shopSearchViewAPI;
        this.context = context;
        shopSearchModle = new ShopSearchModle();
    }


    public void getGoodsData(String url, String keywords, String page) {
        Map<String, String> map = new HashMap<>();
        map.put("keywords", keywords);
        map.put("page", page);
        shopSearchModle.getData(url,map, new ShopSearchPresenterAPI() {
            @Override
            public void success(Object o) {
                shopSearchViewAPI.getSuccess(o);
            }


            @Override
            public void failed(Exception e) {
                shopSearchViewAPI.getFailed(e);
            }
        });
    }




}

//接口l类ShopSearchPresenterAPI 

public interface ShopSearchPresenterAPI {
    void success(Object o);


    void failed(Exception e);

}

//接口类ShopSearchViewAPI 

public interface ShopSearchViewAPI {
    void getSuccess(Object o);


    void getFailed(Exception e);

}



//MianActivity副本

<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="com.example.administrator.zuoyehehe.view.MainActivity">


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


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:gravity="center"
            android:text="搜索商品" />


        <ImageView
            android:id="@+id/cutImg"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:layout_margin="7dp"
            android:src="@drawable/kind_grid" />


    </RelativeLayout>


    <TextView
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="#c0c0c0" />


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


        <EditText
            android:id="@+id/editKey"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="请输入关键字" />


        <Button
            android:id="@+id/btnSearch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="搜索" />


    </LinearLayout>


    <TextView
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="#c0c0c0" />


    <com.jcodecraeer.xrecyclerview.XRecyclerView
        android:id="@+id/xrecyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></com.jcodecraeer.xrecyclerview.XRecyclerView>


</LinearLayout>



//grid_icon布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">


    <ImageView
        android:id="@+id/GoodsIcon"
        android:layout_width="80dp"
        android:layout_height="80dp" />


    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="asdasd" />




    <TextView
        android:id="@+id/price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="asdasd" />


    <TextView
        android:id="@+id/bargainPrice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="asdasd"
        android:textColor="#f00" />

</LinearLayout>



//lv_icon布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">


    <ImageView
        android:id="@+id/GoodsIcon"
        android:layout_width="80dp"
        android:layout_height="80dp" />


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


        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="asdasd" />


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


            <TextView
                android:id="@+id/price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="asdasd" />


            <TextView
                android:id="@+id/bargainPrice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="asdasd"
                android:textColor="#f00" />
        </LinearLayout>


    </LinearLayout>


</LinearLayout>



//所以依赖

  implementation fileTree(dir: 'libs', include: ['*.jar'])
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.squareup.okio:okio:1.5.0'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    compile 'com.jcodecraeer:xrecyclerview:1.3.2'
    compile 'com.github.bumptech.glide:glide:3.7.0'}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值