仿京东搜索页面

HttpUtils

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

----------------------------------------------------------------------------------------------------------

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

}

------------------------------------------------------------------------------------------------------------

Modle包

GetGoodsListener

public interface GetGoodsListener {
    void getSuccess(String json);

    void getError(String error);
}

---------------------------------------------------------------------------------------------------------------

Bean包省略

---------------------------------------------------------------------------------------------------------------

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

}

---------------------------------------------------------------------------------------------------------------

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

}

-----------------------------------------------------------------------------------------------------------------

Presenter包

public interface IPresenter {
    void showGoodsListToView(IModel iModel, IMainView iMainView);

}

--------------------------------------------------------------------------------------------------------------------------

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

}

---------------------------------------------------------------------------------------------------------------------

view 包

public interface IMainView {
    //显示商品也

    void showGoodsList(List<GoodsListBean.DataBean> list);


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

}

----------------------------------------------------------------------------------------------------------------------

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

}

--------------------------------------------------------------------------------------------------------------------------------

搜索框组合控件

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

}

-------------------------------------------------------------------------------------------------------------------------------

动画页面

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

}

-------------------------------------------------------------------------------------------------------------------------------

MyAdapter

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

}

--------------------------------------------------------------------------------------------------------------------------

组合控件XML

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

-----------------------------------------------------------------------------------------------------------------------

主页面XML

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

猜你喜欢

转载自blog.csdn.net/zyanna/article/details/80102531