OkHttp的网络请求数据和RecyclerView的多条目加载,添加分割线
要导入RecyclerView的依赖
还要导入OkHttp Okio 两个架包
切记要在清单文件里写上网络权限
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.okhttp.Bean.Max;
import com.example.okhttp.Utils.OkHttp3Utils;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* OkHttp 请求网络数据
* RecyclerView 多条目加载
* RecyclerView 添加分割线
*/
public class MainActivity extends AppCompatActivity {
//定义一个网址,接口
String str = "http://m.yunifang.com/yunifang/mobile/category/list?random=96333&encode=bf3386e14fe5bb0bcef234baebca2414";
RecyclerView rv;
Max max;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找控件
rv = (RecyclerView) findViewById(R.id.rv);
//初始化ImageLoader
ImageLoaderConfiguration cofn = ImageLoaderConfiguration.createDefault(this);
ImageLoader.getInstance().init(cofn);
DisplayImageOptions simple = DisplayImageOptions.createSimple();
okURL();
init();
}
// 样式
private void init() {
//LinearLayoutManager布局样式
// LinearLayoutManager manager=new LinearLayoutManager(this);
// GridLayoutManager布局样式
GridLayoutManager manager = new GridLayoutManager(this, 2);
//设置样式
rv.setLayoutManager(manager);
//设置方向 VERTICAL垂直方向
//想要添加分割线,必须要写上这行代码
rv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
}
//okhttp的网络请求
private void okURL() {
OkHttp3Utils.doGet(str, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//Gson解析
Gson gson = new Gson();
String strs = response.body().string();
max = gson.fromJson(strs, Max.class);
//判断call,如果返回ture就继续执行,否则就不行
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//创建适配器
Myadapter adapter = new Myadapter();
//设置适配器
rv.setAdapter(adapter);
//刷新适配器
adapter.notifyDataSetChanged();
}
});
}
}
});
}
//创建适配器
class Myadapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int TYPE_ONE=0;
public static final int TYPE_TWO=1;
private MyViewHolder holder1;
private MyViewHolder1 holder2;
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//把两个item布局加载进来
if (viewType==TYPE_ONE){
//item1布局
View view1=View.inflate(MainActivity.this,R.layout.item2,null);
//实例化Holder1
holder1 = new MyViewHolder(view1);
return holder1;
}else {
//item1布局
View view2=View.inflate(MainActivity.this,R.layout.item1,null);
//实例化Holder2
holder2 = new MyViewHolder1(view2);
return holder2;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder1 instanceof MyViewHolder){
holder1.tv.setText(max.getData().getGoodsBrief().get(position).getGoods_name());
ImageLoader.getInstance().displayImage(max.getData().getGoodsBrief().get(position).getGoods_img(),holder1.iv);
}
if(holder2 instanceof MyViewHolder1){
holder2.tv.setText(max.getData().getGoodsBrief().get(position).getGoods_name());
ImageLoader.getInstance().displayImage(max.getData().getGoodsBrief().get(position).getGoods_img(),holder2.iv);
}
}
//想要实现多条目必须重写此方法
@Override
public int getItemViewType(int position) {
if (position%2==0){
return TYPE_ONE;
}else {
return TYPE_TWO;
}
}
@Override
public int getItemCount() {
return max.getData().getGoodsBrief()==null ? 0 :max.getData().getGoodsBrief().size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv;
ImageView iv;
public MyViewHolder(View itemView) {
super(itemView);
tv = itemView.findViewById(R.id.tv);
iv=itemView.findViewById(R.id.iv);
}
}
class MyViewHolder1 extends RecyclerView.ViewHolder {
TextView tv;
ImageView iv;
public MyViewHolder1(View itemView) {
super(itemView);
tv = itemView.findViewById(R.id.tv);
iv=itemView.findViewById(R.id.iv);
}
}
}
}
/**
* OkHttp的封装类
*/
package com.example.okhttp.Utils;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* OkHttp的封装类
*/
public class OkHttp3Utils {
private static OkHttpClient okHttpClient = null;
public OkHttp3Utils() {
}
private static OkHttpClient getOkHttpClient() {
synchronized (OkHttp3Utils.class) {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient();
}
}
return okHttpClient;
}
//上传文件
public static void loadFile(String url, File file,String fileName){
OkHttpClient okHttpClient = getOkHttpClient();
//设置文件类型
RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"),file);
//设置请求体
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image",fileName,requestBody)
.build();
//请求方式
Request request = new Request.Builder().url(url).post(body).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("成功","成功");
}
});
}
/**
* 1.接口地址
* 2.接口回调
*/
public static void doGet(String url,Callback callback){
OkHttpClient okHttpClient = getOkHttpClient();
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(callback);
}
/**
* 1.地址
* 2.接口回调
* 3.请求体
*/
public static void doPost(String url, Map<String,String> map,Callback callback){
OkHttpClient okHttpClient = getOkHttpClient();
FormBody.Builder builder = new FormBody.Builder();
//遍历map集合 设置请求体
for (String mapKey : map.keySet()){
builder.add(mapKey,map.get(mapKey));
}
//设置请求方式
Request request = new Request.Builder().url(url).post(builder.build()).build();
//执行请求方式 接口回调
okHttpClient.newCall(request).enqueue(callback);
}
/**
*1.下载地址
*/
public static void doDown(String url,Callback callback){
OkHttpClient okHttpClient = getOkHttpClient();
Request build = new Request.Builder().url(url).build();
okHttpClient.newCall(build).enqueue(callback);
}
}
//御泥坊的接口
http://m.yunifang.com/yunifang/mobile/category/list?random=96333&encode=bf3386e14fe5bb0bcef234baebca2414
//解析的数据
Max类
package com.example.okhttp.Bean;
import java.util.List;
/**
* Created by tangxiaoying on 2017/10/15.
* Gson的bean类
*/
public class Max {
/**
* code : 200
* msg : success
* data : {"category":[{"id":"16","cat_name":"按功效","is_leaf":"0","children":[{"id":"17","cat_name":"补水保湿","is_leaf":"1"},{"id":"31","cat_name":"舒缓修护","is_leaf":"1"},{"id":"19","cat_name":"控油去痘","is_leaf":"1"},{"id":"18","cat_name":"美白提亮","is_leaf":"1"},{"id":"20","cat_name":"紧致抗皱","is_leaf":"1"}]},{"id":"6","cat_name":"按属性","is_leaf":"0","children":[{"id":"38","cat_name":"面膜","is_leaf":"0"},{"id":"39","cat_name":"润肤水","is_leaf":"1"},{"id":"40","cat_name":"润肤乳","is_leaf":"1"},{"id":"24","cat_name":"洁面乳","is_leaf":"0"},{"id":"35","cat_name":"其他","is_leaf":"0"},{"id":"33","cat_name":"实惠套装","is_leaf":"1"},{"id":"9","cat_name":"贴式面膜","is_leaf":"0"},{"id":"10","cat_name":"睡眠面膜","is_leaf":"0"},{"id":"23","cat_name":"泥浆面膜","is_leaf":"0"},{"id":"41","cat_name":"男士","is_leaf":"0"}]},{"id":"11","cat_name":"按肤质","is_leaf":"0","children":[{"id":"14","cat_name":"混合性肤质","is_leaf":"1"},{"id":"13","cat_name":"中性肤质","is_leaf":"1"},{"id":"29","cat_name":"干性肤质","is_leaf":"1"},{"id":"28","cat_name":"油性肤质","is_leaf":"1"},{"id":"15","cat_name":"痘痘肤质","is_leaf":"1"},{"id":"37","cat_name":"敏感肤质","is_leaf":"0"}]}],"goodsBrief":[{"id":"121","goods_name":"镇店之宝丨美白嫩肤面膜7片","shop_price":49.9,"market_price":99,"goods_img":"https://image.yunifang.com/yunifang/images/goods/121/goods_img/17062610568378169043195978.jpg","reservable":false,"efficacy":"镇店之宝
美白爆款","stock_number":0,"restrict_purchase_num":0},{"id":"389","goods_name":"热销爆款丨清爽平衡矿物黑面膜21片","shop_price":99.9,"market_price":297,"goods_img":"https://image.yunifang.com/yunifang/images/goods/389/goods_img/17062610265116850439553337.jpg","reservable":false,"efficacy":"以黑吸黑
净透亮肤","stock_number":0,"restrict_purchase_num":0},{"id":"684","goods_name":"解救肌渴丨花粹水润面膜套装10片","shop_price":29.9,"market_price":139,"goods_img":"https://image.yunifang.com/yunifang/images/goods/684/goods_img/17062610401397749701177609.jpg","reservable":false,"efficacy":"水润充盈
鲜嫩少女肌","stock_number":0,"restrict_purchase_num":0},{"id":"6","goods_name":"好用不贵丨亮颜水润蚕丝面膜(寂地定制版)","shop_price":59.9,"market_price":239.9,"goods_img":"https://image.yunifang.com/yunifang/images/goods/6/goods_img/170626112597120167739086821.jpg","reservable":false,"efficacy":"深层补水
提亮肤色","stock_number":0,"restrict_purchase_num":0},{"id":"772","goods_name":"买就赠黑糖7片丨清润莹亮黑膜套装21片","shop_price":79.9,"market_price":297,"goods_img":"https://image.yunifang.com/yunifang/images/goods/772/goods_img/170929144736019579343521099.jpg","reservable":false,"efficacy":"自然莹亮
水感瓷肌","stock_number":0,"restrict_purchase_num":0},{"id":"5","goods_name":"金桂花矿物眼膜贴60片","shop_price":49.9,"market_price":89,"goods_img":"https://image.yunifang.com/yunifang/images/goods/5/goods_img/170626112553213363513709796.jpg","reservable":false,"efficacy":"补水靓眼
改善熊猫眼","stock_number":0,"restrict_purchase_num":0},{"id":"343","goods_name":"美白嫩肤润肤水150ml","shop_price":69,"market_price":119,"goods_img":"https://image.yunifang.com/yunifang/images/goods/343/goods_img/170626103423611420000294568.jpg","reservable":false,"efficacy":"补水保湿
美白嫩肤","stock_number":0,"restrict_purchase_num":0},{"id":"9","goods_name":"玫瑰滋养矿物睡眠面膜180g","shop_price":59.9,"market_price":99,"goods_img":"https://image.yunifang.com/yunifang/images/goods/9/goods_img/170626112611018894167156705.jpg","reservable":false,"efficacy":"镇店之宝
彻夜补水","stock_number":0,"restrict_purchase_num":0},{"id":"10","goods_name":"包邮丨美白嫩肤睡眠面膜180g","shop_price":49.9,"market_price":99,"goods_img":"https://image.yunifang.com/yunifang/images/goods/10/goods_img/170626112190919312919673075.jpg","reservable":false,"efficacy":"补水美白
越睡越白","stock_number":0,"restrict_purchase_num":0},{"id":"446","goods_name":"芦荟补水保湿凝胶150g","shop_price":49.9,"market_price":89,"goods_img":"https://image.yunifang.com/yunifang/images/goods/446/goods_img/170627143627211691152946151.jpg","reservable":false,"efficacy":"水水润润
修护受损","stock_number":0,"restrict_purchase_num":0},{"id":"16","goods_name":"热销套装丨玫瑰滋养保湿四件套","shop_price":139.9,"market_price":259.9,"goods_img":"https://image.yunifang.com/yunifang/images/goods/16/goods_img/17062611152592656236701367.jpg","reservable":false,"efficacy":"一整套源源补水","stock_number":0,"restrict_purchase_num":0},{"id":"8","goods_name":"买就送素颜霜丨美白嫩肤面膜20片","shop_price":119.9,"market_price":359,"goods_img":"https://image.yunifang.com/yunifang/images/goods/8/goods_img/170929144780917903477663517.jpg","reservable":false,"efficacy":"真美白
匠心造","stock_number":0,"restrict_purchase_num":0},{"id":"14","goods_name":"买就送洗脸扑丨矿物泥浆鼻膜60g","shop_price":55,"market_price":69,"goods_img":"https://image.yunifang.com/yunifang/images/goods/14/goods_img/170930094138819848945676015.jpg","reservable":false,"efficacy":"草莓鼻小救星
收敛毛孔","stock_number":0,"restrict_purchase_num":0},{"id":"189","goods_name":"控油必备丨清爽平衡护肤三件套","shop_price":99.9,"market_price":179.9,"goods_img":"https://image.yunifang.com/yunifang/images/goods/189/goods_img/1709300953684984597198733.jpg","reservable":false,"efficacy":"深层清洁
平衡水油","stock_number":0,"restrict_purchase_num":0},{"id":"428","goods_name":"多彩水润亮颜蚕丝面膜套装21片","shop_price":79.9,"market_price":270.9,"goods_img":"https://image.yunifang.com/yunifang/images/goods/428/goods_img/17062610201873359203247864.jpg","reservable":false,"efficacy":"吸黑焕彩
补水保湿","stock_number":0,"restrict_purchase_num":0}]}
*/
private int code;
private String msg;
private DataEntity data;
public void setCode(int code) {
this.code = code;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setData(DataEntity data) {
this.data = data;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public DataEntity getData() {
return data;
}
public static class DataEntity {
/**
* id : 16
* cat_name : 按功效
* is_leaf : 0
* children : [{"id":"17","cat_name":"补水保湿","is_leaf":"1"},{"id":"31","cat_name":"舒缓修护","is_leaf":"1"},{"id":"19","cat_name":"控油去痘","is_leaf":"1"},{"id":"18","cat_name":"美白提亮","is_leaf":"1"},{"id":"20","cat_name":"紧致抗皱","is_leaf":"1"}]
*/
private List<CategoryEntity> category;
/**
* id : 121
* goods_name : 镇店之宝丨美白嫩肤面膜7片
* shop_price : 49.9
* market_price : 99.0
* goods_img : https://image.yunifang.com/yunifang/images/goods/121/goods_img/17062610568378169043195978.jpg
* reservable : false
* efficacy : 镇店之宝 美白爆款
* stock_number : 0
* restrict_purchase_num : 0
*/
private List<GoodsBriefEntity> goodsBrief;
public void setCategory(List<CategoryEntity> category) {
this.category = category;
}
public void setGoodsBrief(List<GoodsBriefEntity> goodsBrief) {
this.goodsBrief = goodsBrief;
}
public List<CategoryEntity> getCategory() {
return category;
}
public List<GoodsBriefEntity> getGoodsBrief() {
return goodsBrief;
}
public static class CategoryEntity {
private String id;
private String cat_name;
private String is_leaf;
/**
* id : 17
* cat_name : 补水保湿
* is_leaf : 1
*/
private List<ChildrenEntity> children;
public void setId(String id) {
this.id = id;
}
public void setCat_name(String cat_name) {
this.cat_name = cat_name;
}
public void setIs_leaf(String is_leaf) {
this.is_leaf = is_leaf;
}
public void setChildren(List<ChildrenEntity> children) {
this.children = children;
}
public String getId() {
return id;
}
public String getCat_name() {
return cat_name;
}
public String getIs_leaf() {
return is_leaf;
}
public List<ChildrenEntity> getChildren() {
return children;
}
public static class ChildrenEntity {
private String id;
private String cat_name;
private String is_leaf;
public void setId(String id) {
this.id = id;
}
public void setCat_name(String cat_name) {
this.cat_name = cat_name;
}
public void setIs_leaf(String is_leaf) {
this.is_leaf = is_leaf;
}
public String getId() {
return id;
}
public String getCat_name() {
return cat_name;
}
public String getIs_leaf() {
return is_leaf;
}
}
}
public static class GoodsBriefEntity {
private String id;
private String goods_name;
private double shop_price;
private double market_price;
private String goods_img;
private boolean reservable;
private String efficacy;
private int stock_number;
private int restrict_purchase_num;
public void setId(String id) {
this.id = id;
}
public void setGoods_name(String goods_name) {
this.goods_name = goods_name;
}
public void setShop_price(double shop_price) {
this.shop_price = shop_price;
}
public void setMarket_price(double market_price) {
this.market_price = market_price;
}
public void setGoods_img(String goods_img) {
this.goods_img = goods_img;
}
public void setReservable(boolean reservable) {
this.reservable = reservable;
}
public void setEfficacy(String efficacy) {
this.efficacy = efficacy;
}
public void setStock_number(int stock_number) {
this.stock_number = stock_number;
}
public void setRestrict_purchase_num(int restrict_purchase_num) {
this.restrict_purchase_num = restrict_purchase_num;
}
public String getId() {
return id;
}
public String getGoods_name() {
return goods_name;
}
public double getShop_price() {
return shop_price;
}
public double getMarket_price() {
return market_price;
}
public String getGoods_img() {
return goods_img;
}
public boolean isReservable() {
return reservable;
}
public String getEfficacy() {
return efficacy;
}
public int getStock_number() {
return stock_number;
}
public int getRestrict_purchase_num() {
return restrict_purchase_num;
}
}
}
}
布局
activity布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.okhttp.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv"
android:layout_width="match_parent"
android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
item1布局
<?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="vertical"
>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
/>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="haha"
android:textSize="8sp"
android:layout_marginLeft="20dp"
/>
</LinearLayout>
item2布局
<?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="vertical"
>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
/>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="haha"
android:textSize="8sp"
android:layout_marginLeft="20dp"
/>
</LinearLayout>
RecyclerView添加分割线
注意样式里面不能写汉字,不然会报错
在Drawable里创建一个分割线样式
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
<!-- 线开始的颜色 -->
android:startColor="#ffff0000"
<!-- 线中间颜色 -->
android:centerColor="#ff00ff00"
<!-- 线中间颜色 -->
android:endColor="#ff0000ff"
<!-- 线的样式 -->
android:type="linear"
></gradient>
<!-- 线的高度 -->
<size android:height="4dp"></size>
</shape>
在Style里引入
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- 引入分割线的样式 -->
<item name="android:listDivider">@drawable/fengexian</item>
</style>
</resources>
实现效果