搜索框加切换布局

首先添加的依赖

compile 'com.squareup.okhttp3:okhttp:3.3.0'



    compile 'com.github.bumptech.glide:glide:3.7.0'


    compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'

以下为布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.daydayup.day15_lianxi.view.MainActivity">

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

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="商品列表"
            android:textSize="25sp" />

        <ImageView
            android:id="@+id/change"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:src="@drawable/kind_grid" />
    </LinearLayout>


    <View
        android:layout_width="match_parent"
        android:layout_height="0.75dp" />


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

        <com.daydayup.day15_lianxi.view.MySearchView
            android:id="@+id/mysearch"
            android:layout_width="0dp"
            android:layout_height="55dp"
            android:layout_weight="1"></com.daydayup.day15_lianxi.view.MySearchView>

        <TextView
            android:id="@+id/sousuo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="搜索"
            android:textSize="20sp" />

    </LinearLayout>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>

</LinearLayout>

activity_splash2

<?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">

    <ImageView
        android:id="@+id/splash_pic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:src="@mipmap/ic_launcher" />

</LinearLayout>

item_layout

<?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="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/item_pic"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@mipmap/ic_launcher" />

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

        <TextView
            android:id="@+id/itme_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="标题" />

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

            <TextView
                android:id="@+id/item_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="价格" />

            <TextView
                android:id="@+id/item_price2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="折扣价格" />
        </LinearLayout>


    </LinearLayout>

</LinearLayout>

layout_search

<?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="wrap_content"
    android:background="@drawable/search_bg"
    android:orientation="horizontal"
    android:padding="8dp">

    <ImageView
        android:layout_width="@dimen/search_height"
        android:layout_height="@dimen/search_height"
        android:src="@drawable/a_4" />

    <EditText
        android:id="@+id/search_content"
        android:layout_width="0dp"
        android:layout_height="@dimen/search_height"
        android:layout_weight="1"
        android:background="@null" />

    <ImageView
        android:layout_width="@dimen/search_height"
        android:layout_height="@dimen/search_height"
        android:src="@drawable/root" />

</LinearLayout>

以下为主Activity

package com.daydayup.day15_lianxi.view;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.daydayup.day15_lianxi.R;
import com.daydayup.day15_lianxi.adapters.MyAdapter;
import com.daydayup.day15_lianxi.model.GoodsListBean;
import com.daydayup.day15_lianxi.model.ModelImpl;
import com.daydayup.day15_lianxi.presenter.PresenterImpl;

import java.util.List;

public class MainActivity extends AppCompatActivity implements IMainView, View.OnClickListener {
    private static final String TAG = "MainActivity-----";
    private RecyclerView recyclerView;
    private MySearchView mySearchView;
    private TextView sousuo;
    private PresenterImpl presenter;
    private boolean flag = true;
    private ImageView change;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化界面
        initViews();
        //初始化数据
        initDatas();
    }

    private void initDatas() {
        presenter = new PresenterImpl();
        presenter.showGoodsListToView(new ModelImpl(), this);
    }

    private void initViews() {
        recyclerView = findViewById(R.id.recyclerView);
        mySearchView = findViewById(R.id.mysearch);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        sousuo = findViewById(R.id.sousuo);
        sousuo.setOnClickListener(this);

        change = findViewById(R.id.change);
        change.setOnClickListener(this);
    }

    //显示商品列表
    @Override
    public void showGoodsList(List<GoodsListBean.DataBean> list) {
        Log.d(TAG, "showGoodsList: " + list);
        MyAdapter myAdapter = new MyAdapter(MainActivity.this, list);
        recyclerView.setAdapter(myAdapter);
    }

    @Override
    public String getContent() {
        String content = mySearchView.getContent();
        if (TextUtils.isEmpty(content)) {
            content = "笔记本";
        }
        return content;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sousuo:

                presenter.showGoodsListToView(new ModelImpl(), this);

                break;

            case R.id.change:

                if (flag) {
                    recyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
                    change.setImageResource(R.drawable.kind_liner);
                } else {
                    recyclerView.setLayoutManager(new LinearLayoutManager(this));
                    change.setImageResource(R.drawable.kind_grid);
                }
                flag = !flag;
                break;
        }
    }
}

以下为view层

IMainView

public interface IMainView {
    //显示商品也
    void showGoodsList(List<GoodsListBean.DataBean> list);

    //获取输入框内容
    String getContent();

}
MySearchView
package com.daydayup.day15_lianxi.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.daydayup.day15_lianxi.R;

/**
 * 1.组合控件
 * 将原有的控件组合起来成为一个整体---控件
 * <p>
 * 1.根据需求,写布局文件
 * 2.布局文件---View
 * 3.逻辑
 * <p>
 * 2.自定义View
 * 3.自定义ViewGroup
 * <p>
 * 构造
 * onDraw
 * 绘制,文字,图片,颜色,形状
 * onMeasure
 * 测量
 * onLayout
 * 布局
 * onSizeChange
 * 当控件大小改变是调用
 * onTouchEvent
 * 处理触摸事件
 */

public class MySearchView extends LinearLayout {

    private EditText search_content;

    //1.
    //直接new的时候
    public MySearchView(Context context) {
        this(context, null);
    }

    public MySearchView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    //在布局文件里面时候控件的时候
    public MySearchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //初始化
        View view = View.inflate(context, R.layout.layout_search, this);
        search_content = view.findViewById(R.id.search_content);
//        search_content.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                search_content.setFocusable(true);
//            }
//        });
    }

    //获取输入的内容

    public String getContent() {
        return search_content.getText().toString();
    }

}
SplashActivity
package com.daydayup.day15_lianxi.view;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.daydayup.day15_lianxi.R;

public class SplashActivity extends AppCompatActivity {

    private int width;
    private int height;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_splash2);
        //获取屏幕宽高
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();

        //初始化页面
        initViews();
    }

    private void initViews() {
        ImageView imageView=findViewById(R.id.splash_pic);
        //属性动画
        ObjectAnimator translationY = ObjectAnimator.ofFloat(imageView, "translationY", 0, height / 2);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(imageView, "scaleX", 2, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(imageView, "scaleY", 2, 1);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(imageView, "alpha", 0, 1);
        ObjectAnimator rotation = ObjectAnimator.ofFloat(imageView, "rotation", 360);

        //添加到动画集合
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(translationY,scaleX,scaleY,alpha,rotation);

        //设置
        animatorSet.setDuration(3000);
        animatorSet.start();
        animatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                //动画结束的时候,跳转页面
                Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(intent);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

    }
}

以下为presenter层

IPresenter

public interface IPresenter {
    void showGoodsListToView(IModel iModel, IMainView iMainView);
}
PresenterImpl
public class PresenterImpl implements IPresenter {
    private static final String TAG = "PresenterImpl---";
    @Override
    public void showGoodsListToView(IModel iModel, final IMainView iMainView) {
        Map<String,String> map = new HashMap<>();
        map.put("keywords",iMainView.getContent());
        map.put("page","1");
        iModel.getGoodsListData(HttpConfig.goodslist_url, map, new GetGoodsListener() {
            @Override
            public void getSuccess(String json) {
                Log.d(TAG, "数据----: "+json);
                Gson gson = new Gson();
                GoodsListBean goodsListBean = gson.fromJson(json, GoodsListBean.class);
                List<GoodsListBean.DataBean> list = goodsListBean.getData();
                //放入view
                iMainView.showGoodsList(list);
            }

            @Override
            public void getError(String error) {
                Log.d(TAG, "getError: "+error);
            }
        });
    }
}

以下为model层

GetGoodsListener

public interface GetGoodsListener {
    void getSuccess(String json);

    void getError(String error);
}

GoodsListBean

public class GoodsListBean {

    /**
     * msg : 查询成功
     * code : 0
     * data : [{"bargainPrice":11800,"createtime":"2017-10-14T21:48:08","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","itemtype":2,"pid":77,"price":38999.99,"pscid":40,"salenum":7757,"sellerid":21,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"},{"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","itemtype":1,"pid":66,"price":13000,"pscid":40,"salenum":7676,"sellerid":10,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"},{"bargainPrice":11800,"createtime":"2017-10-03T23:53:28","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","itemtype":0,"pid":76,"price":37999.99,"pscid":40,"salenum":6868,"sellerid":20,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"},{"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","itemtype":1,"pid":69,"price":16999,"pscid":40,"salenum":6645,"sellerid":13,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"},{"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","itemtype":1,"pid":61,"price":14999,"pscid":40,"salenum":5535,"sellerid":5,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"},{"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","itemtype":1,"pid":75,"price":36999,"pscid":40,"salenum":5454,"sellerid":19,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"},{"bargainPrice":11800,"createtime":"2017-10-03T23:53:28","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","itemtype":0,"pid":79,"price":888,"pscid":40,"salenum":5454,"sellerid":23,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"},{"bargainPrice":11800,"createtime":"2017-10-10T17:33:37","detailUrl":"https://item.m.jd.com/product/4338107.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6700/155/2098998076/156185/6cf95035/595dd5a5Nc3a7dab5.jpg!q70.jpg","itemtype":0,"pid":57,"price":5199,"pscid":40,"salenum":4343,"sellerid":1,"subhead":"【i5 MX150 2G显存】全高清窄边框 8G内存 256固态硬盘 支持指纹识别 预装WIN10系统","title":"小米(MI)Air 13.3英寸全金属轻薄笔记本(i5-7200U 8G 256G PCle SSD MX150 2G独显 FHD 指纹识别 Win10)银 "},{"bargainPrice":11800,"createtime":"2017-10-03T23:53:28","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","itemtype":0,"pid":71,"price":32999,"pscid":40,"salenum":4242,"sellerid":15,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"},{"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","itemtype":1,"pid":63,"price":10000,"pscid":40,"salenum":3232,"sellerid":7,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}]
     * 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 : 11800
         * createtime : 2017-10-14T21:48:08
         * 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
         * itemtype : 2
         * pid : 77
         * price : 38999.99
         * pscid : 40
         * salenum : 7757
         * sellerid : 21
         * subhead : 购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)
         * title : 全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G
         */

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

        public double getBargainPrice() {
            return bargainPrice;
        }

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

        public String getCreatetime() {
            return createtime;
        }

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

        public String getDetailUrl() {
            return detailUrl;
        }

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

        public String getImages() {
            return images;
        }

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

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

IModel

public interface IModel {
    //获取商品列表数据
    void getGoodsListData(String url, Map<String,String> map,GetGoodsListener getGoodsListener);
}

ModelImpl

package com.daydayup.day15_lianxi.model;

import com.daydayup.day15_lianxi.http.HttpUtils;
import com.daydayup.day15_lianxi.http.OkLoadListener;

import java.util.Map;

/**
 * Created by gjl on 2018/4/26.
 */

public class ModelImpl implements IModel {
    @Override
    public void getGoodsListData(String url, Map<String, String> map, final GetGoodsListener getGoodsListener) {
        HttpUtils httpUtils = HttpUtils.getHttpUtils();
        httpUtils.okPost(url, map);
        httpUtils.setOkLoadListener(new OkLoadListener() {
            @Override
            public void okLoadSuccess(String json) {
                getGoodsListener.getSuccess(json);
            }

            @Override
            public void okLoadError(String error) {
                getGoodsListener.getError(error);
            }
        });
    }
}

以下是http

HttpConfig

public class HttpConfig {
    public static String goodslist_url = "http://120.27.23.105/product/searchProducts";
}

HttpUtils

package com.daydayup.day15_lianxi.http;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

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

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

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

public class HttpUtils {
    private static final String TAG = "HttpUtils-----";
    private static HttpUtils httpUtils;
    private final int SUCCESS = 0;
    private final int ERROR = 1;
    private MyHandler myHandler = new MyHandler();
    private OkLoadListener okLoadListener;

    public static HttpUtils getHttpUtils() {
        if (httpUtils == null) {
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    //成功
                    String json = (String) msg.obj;
                    okLoadListener.okLoadSuccess(json);
                    break;

                case ERROR:
                    //失败
                    String error = (String) msg.obj;
                    okLoadListener.okLoadError(error);
                    break;
            }
        }
    }

    //get
    public void okGet(String url) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyIntercepter()).build();

        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = myHandler.obtainMessage();
                message.what = ERROR;
                message.obj = e.getMessage();
                myHandler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = myHandler.obtainMessage();
                message.what = SUCCESS;
                message.obj = response.body().string();
                myHandler.sendMessage(message);
            }
        });
    }

    public void setOkLoadListener(OkLoadListener okLoadListener) {
        this.okLoadListener = okLoadListener;
    }

    //post
    public void okPost(String url, Map<String, String> params) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyIntercepter()).build();

        FormBody.Builder builder = new FormBody.Builder();
        Set<String> keySet = params.keySet();
        for (String key :
                keySet) {
            String value = params.get(key);
            builder.add(key, value);
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder().url(url).post(formBody).build();
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = myHandler.obtainMessage();
                message.what = ERROR;
                message.obj = e.getMessage();
                myHandler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = myHandler.obtainMessage();
                message.what = SUCCESS;
                message.obj = response.body().string();
                myHandler.sendMessage(message);
            }
        });

    }

    //拦截器
    class MyIntercepter implements Interceptor {
        //intercept 拦截
        @Override
        public Response intercept(Chain chain) throws IOException {
            //添加公共参数
			//post 取出原来所有的参数,将之加到新的请求体里面。然后让请求去执行
            Request request = chain.request();
            //获取请求方法
            String method = request.method();
            if (method.equals("GET")) {//---------------------------GET 拦截
                //取出url地址
                String url = request.url().toString();
                //拼接公共参数
                boolean contains = url.contains("?");
                if (contains) {
                    url = url + "&source=android";
                } else {
                    url = url + "?source=android";
                }

                Request request1 = request.newBuilder().url(url).build();

                Response response = chain.proceed(request1);

                return response;


            } else if (method.equals("POST")) {//---------------------POST 拦截
                RequestBody body = request.body();//请求体
                if (body instanceof FormBody) {
                    //创建新的请求体
                    FormBody.Builder newBuilder = new FormBody.Builder();
                    for (int i = 0; i < ((FormBody) body).size(); i++) {
                        String key = ((FormBody) body).name(i);
                        String value = ((FormBody) body).value(i);
                        newBuilder.add(key, value);
                    }
                    //添加公共参数
                    newBuilder.add("source", "android");
                    FormBody newBody = newBuilder.build();
                    //创建新的请求体
                    Request request1 = request.newBuilder().post(newBody).build();
                    //去请求
                    Response response = chain.proceed(request1);
                    return response;
                }
            }
            return null;
        }
    }

    //上传文件(图片)
    public void upLoadImage(String url, String path) {//url 要上传的地址。path 要上传的文件路径
        //媒体类型
        MediaType mediaType = MediaType.parse("image/*");
        //multipartbody
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File file = new File(path);
        MultipartBody multipartBody = builder.addFormDataPart("file", file.getName(), RequestBody.create(mediaType, file)).build();

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).post(multipartBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "上传失败0----: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "上传成功: ");
            }
        });

    }
}
OkLoadListener
public interface OkLoadListener {
    void okLoadSuccess(String json);

    void okLoadError(String error);
}

最后适配器

package com.daydayup.day15_lianxi.adapters;

import android.content.Context;
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.daydayup.day15_lianxi.R;
import com.daydayup.day15_lianxi.model.GoodsListBean;

import java.util.List;

/**
 * Created by gjl on 2018/4/26.
 */

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private Context context;
    private List<GoodsListBean.DataBean> list;

    public MyAdapter(Context context, List<GoodsListBean.DataBean> list) {

        this.list = list;
        this.context = context;

    }


    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false);
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        String pic_url = list.get(position).getImages().split("\\|")[0];
        Glide.with(context).load(pic_url).into(holder.getImageView());


        holder.getTitle().setText(list.get(position).getTitle());
        holder.getPrice().setText(list.get(position).getPrice() + "");
        holder.getPrice2().setText(list.get(position).getBargainPrice() + "");

    }

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

    class MyViewHolder extends RecyclerView.ViewHolder {

        private final ImageView imageView;
        private final TextView title;
        private final TextView price;
        private final TextView price2;

        public MyViewHolder(View itemView) {
            super(itemView);
            //找控件
            imageView = itemView.findViewById(R.id.item_pic);
            title = itemView.findViewById(R.id.itme_title);
            price = itemView.findViewById(R.id.item_price);
            price2 = itemView.findViewById(R.id.item_price2);
        }

        public MyViewHolder(View itemView, ImageView imageView, TextView title, TextView price, TextView price2) {
            super(itemView);
            this.imageView = imageView;
            this.title = title;
            this.price = price;
            this.price2 = price2;
        }

        public ImageView getImageView() {
            return imageView;
        }

        public TextView getTitle() {
            return title;
        }

        public TextView getPrice() {
            return price;
        }

        public TextView getPrice2() {
            return price2;
        }
    }


}

猜你喜欢

转载自blog.csdn.net/qq_40857831/article/details/80099272