Recycleview + OkHttpClient二次封装

build.gradle页面

	 **recycleview的依赖**
    api 'com.android.support:recyclerview-v7:27.1.1'
	
	**黄油刀**
	implementation 'com.jakewharton:butterknife:8.7.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.7.0'
	
	**图片加载框架,glide**
	implementation 'com.github.bumptech.glide:glide:3.7.0'

	**okhttp**
	 api 'com.squareup.okhttp3:okhttp:3.12.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.12.0'
	
	**gson**
	implementation 'com.google.code.gson:gson:2.8.5'

**

activity_main,布局不唯一,自行定义

**

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

    <Button
        android:text="请求商品列表"
        android:id="@+id/requestProductBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

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

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

Dpi页面

package com.example.day4.dpi;

public class UserDpi {

    public final static String PRODUCT_URL = "http://www.zhaoapi.cn/product/searchProducts";

}

**

Bean类页面

**

package com.example.day4.entity;

import java.util.List;

public class UserBean {
    public String msg;
    public String code;
    public List<DataBean> data;

    public class DataBean{
        public String images;
        public String title;
    }
}

**

adapter页面

**

package com.example.day4.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
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.day4.R;
import com.example.day4.entity.UserBean;

import java.util.List;

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserVH> {
    private Context context;
    private List<UserBean.DataBean> list;

    //构造方法
    public UserAdapter(Context cont, List<UserBean.DataBean> list) {
        context = cont;
        this.list = list;
    }

    /**
     * 创建viewholder实例
     *
     * @param parent
     * @param viewType
     * @return
     */
    @NonNull
    @Override
    public UserVH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //获取子布局
        View view = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
        //绑定view
        UserVH userVH = new UserVH(view);

        return userVH;
    }

    /**
     * 绑定viewholder
     *
     * @param holder
     * @param position
     */

    @Override
    public void onBindViewHolder(@NonNull final UserVH holder, int position) {
        //创建一个bean的对象,获取list集合的下标
        final UserBean.DataBean bean = list.get(position);
        //设置数据
        holder.title.setText(bean.title);
        String images = bean.images;
        //转义字符
        String[] imgAttr = images.split("\\|");

        if (imgAttr != null && imgAttr.length > 0){//有图片
            //with 绑定组件的生命周期,load加载资源,into给控件显示
            Glide.with(context).load(imgAttr[0]).into(holder.iv);
        }else {//没有图片
            holder.iv.setImageResource(R.mipmap.ic_launcher);
        }

        //点击事件
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemListener != null){
                    itemListener.onItemClickListener(holder.getLayoutPosition(), holder.itemView);
                }
            }
        });

        //长按事件
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (itemListener != null){
                    itemListener.onItemLongClickListener(holder.getLayoutPosition(), holder.itemView);
                }
                return false;
            }
        });
    }

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

    //创建一个寄存器,继承RecylerView.ViewHolder
    class UserVH extends RecyclerView.ViewHolder{
        //声明控件
        private ImageView iv;
        private TextView title;

        public UserVH(View itemView) {
            super(itemView);
            //获取资源ID
            iv = itemView.findViewById(R.id.iv_productIcon);
            title = itemView.findViewById(R.id.tv_title);
        }
    }

    //声明接口
    private ItemListener itemListener;
    //接口的set方法
    public void setItemListener(ItemListener itemListener) {
        this.itemListener = itemListener;
    }

    //创建一个接口
    public interface ItemListener{
        //点击方法
        void onItemClickListener(int pos, View view);
        //长按方法
        void onItemLongClickListener(int pos, View view);
    }
}

**

net包 OkhttpCallback接口页面

**

package com.example.day4.net;

public interface OkhttpCallback {
    //请求服务器失败
    void failure(String msg);
    //数据合法
    void success(String result);
}

OkhttpUtils页面

package com.example.day4.net;

import android.os.Handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * okhttp二次封装,封装网络框架
 *
 */
public class OkhttpUtils {
    //创建一个handler主线程
    private Handler handler = new Handler();
    //声明一个okhttpclient
    private OkHttpClient okHttpClient;
    //私有属性
    private static OkhttpUtils mInstance;

    //私有构造方法
    private OkhttpUtils(){
        //创建log拦截管理器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpClient = new OkHttpClient.Builder()
                //添加log拦截管理器
                .addInterceptor(loggingInterceptor)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();
                //链式调用,构造者模式
    }

    /**
     * 创建实例,双重检验锁,单例模式进行实例化
     *
     * @return
     */
    public static OkhttpUtils getmInstance(){
        if (mInstance == null){
            synchronized (OkhttpUtils.class){
                if (mInstance == null){
                    mInstance = new OkhttpUtils();
                }
            }
        }

        return mInstance;
    }

    /**
     * get请求方式,两个参数,url,okttpCallback接口
     */
    public void doGet(final String url, final OkhttpCallback requestCallback){
        //创建request请求数据
        Request request = new Request.Builder().url(url).get().build();
        //把数据放到newCall
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (requestCallback != null){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            requestCallback.failure("网路异常");
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获取body的数据
                final String result = response.body().string();
                if (requestCallback != null){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            requestCallback.success(result);
                        }
                    });
                }
            }
        });

    }

    /**
     * post请求方式,三个参数,url,hashmap集合,okhttpcallback接口
     */
    public void doPost(String url, HashMap<String,String> params, final OkhttpCallback callback){
        //创建formbody
        FormBody.Builder builder = new FormBody.Builder();

        for (Map.Entry<String,String> map : params.entrySet()){
            builder.add(map.getKey(),map.getValue());
        }

        //创建请求体,接收builder的数据
        RequestBody requestBody = builder.build();

        //创建request,以post方式接收requestbody的数据
        Request request = new Request.Builder().url(url).post(requestBody).build();
        //放到newCall
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                if (callback != null){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.failure("网络异常");
                        }
                    });
                }
            }

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

                if (callback!=null){
                    if (200 == response.code()){
                        final String result = response.body().string();

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.success(result);
                            }
                        });

                    }
                }
            }
        });

    }

    /**
     * 取消所有请求,好处:节省开销:内存开销:CPU的的开销(线程开销)
     *
     */
    public void cancelAllTask(){
        if (okHttpClient!=null){
            okHttpClient.dispatcher().cancelAll();
        }
    }

}

item子条目布局,布局不唯一,可自行定义

<?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:descendantFocusability="blocksDescendants"
    >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        
        <ImageView
            android:id="@+id/iv_productIcon"
            android:layout_width="80dp"
            android:layout_height="80dp" />

        <TextView
            android:layout_marginLeft="10dp"
            android:id="@+id/tv_title"
            android:layout_toRightOf="@id/iv_productIcon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="商品标题"
            />
    </RelativeLayout>


</LinearLayout>

**

MainActivity页面

**

package com.example.day4.activity;

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

import com.example.day4.R;
import com.example.day4.adapter.UserAdapter;
import com.example.day4.dpi.UserDpi;
import com.example.day4.entity.UserBean;
import com.example.day4.net.OkhttpCallback;
import com.example.day4.net.OkhttpUtils;
import com.google.gson.Gson;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    private int page = 1;
    @BindView(R.id.rv_product)
    RecyclerView mrecyclerView;
    @BindView(R.id.requestProductBtn)
    Button requestProductBtn;

    private UserAdapter adapter;
    private List<UserBean.DataBean> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    private void initData(){
        list = new ArrayList<>();
        adapter = new UserAdapter(this, list);
        adapter.setItemListener(new UserAdapter.ItemListener() {
            @Override
            public void onItemClickListener(int pos, View view) {
                Toast.makeText(MainActivity.this, "pos:"+pos, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClickListener(int pos, View view) {

            }
        });

    }

    private void initView(){
        //绑定当前实例
        ButterKnife.bind(this);

        //需要配置布局管理器才能运行,layoutmanager:三种:线性,网格,瀑布流布局管理器
        //ori方向1,垂直 0 水平
        //reverselayout fase正常显示,true倒置

        mrecyclerView.setLayoutManager(new LinearLayoutManager(this, 1, false));

        //mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));
//        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3,1));

    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick(R.id.requestProductBtn)
    public void click(View view){

        HashMap<String, String> params = new HashMap<>();
        params.put("keywords","手机");
        params.put("page",page+"");
        OkhttpUtils.getmInstance().doPost(UserDpi.PRODUCT_URL, params, new OkhttpCallback() {
            @Override
            public void failure(String msg) {

            }

            @Override
            public void success(String result) {
                parseResult(result);
            }
        });

    }

    /**
     * 解析商品列表数据
     *
     * @param result
     */
    private void parseResult(String result){

        UserBean userBean = new Gson().fromJson(result, UserBean.class);
        if (userBean != null){
            adapter = new UserAdapter(this,userBean.data);
            mrecyclerView.setAdapter(adapter);
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值