根据个人习惯进行操作,本人习惯先把包建好
创建UserApi,里面存放网络接口
public class UserApi {
//接口
public final static String USER_API="http://172.17.8.100/small/commodity/v1/findCommodityByKeyword?keyword=板鞋&page=1&count=8";
}
创建UserBean
public class UserBean {
public String message;
public String status;
public List<ResultBean> result;
public static class ResultBean {
public int commodityId;
public String commodityName;
public String masterPic;
public int price;
public int saleNum;
}
}
创建接口,LoadContract契约类
import java.util.HashMap;
import jiaoyibo.bawei.com.zhanshi02.net.RequestCallBack;
/**
* <p>文件描述:契约类<p>
* <p>作者:JYB<p>
* <p>创建时间:2019/2/20<p>
* <p>更改时间:2019/2/20<p>
* <p>版本号:1<p>
*/
public interface LoadContract {
//presenter层
public abstract class LloadPresenter{
public abstract void ppresenter(HashMap<String,String>map);
}
//model层
interface LloadModel{
void model(HashMap<String,String>map, RequestCallBack callBack);
}
//view层
interface LloadView{
void Success(String result);
void failure(String msg);
}
}
创建接口,OkHttpCallBack
public interface OkHttpCallBack {
void Success(String result);
void failure(String msg);
}
创建接口,RequestCallBack
public interface RequestCallBack {
void Success(String result);
void failure(String msg);
}
创建OkHttpUtils工具类
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;
public class OkHttpUtils {
import android.os.Handler;
import java.io.IOException;
import java.sql.Time;
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;
/**
* <p>文件描述:<p>
* <p>作者:JYB<p>
* <p>创建时间:2019/2/20<p>
* <p>更改时间:2019/2/20<p>
* <p>版本号:1<p>
*/
public class OkHttpUtils {
private static OkHttpUtils mInstance;
private final OkHttpClient okHttpClient;
//创建一个主线程的Handler
private Handler handler = new Handler();
//单例模式
public static OkHttpUtils getmInstance(){
if(mInstance==null){
//同步
synchronized (OkHttpUtils.class){
if(mInstance==null){
mInstance = new OkHttpUtils();
}
}
}
return mInstance;
}
//私有构造
private OkHttpUtils(){
//拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
//设置拦截器
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//创建OkHttpClient对象设置时间
okHttpClient = new OkHttpClient.Builder()
//添加拦截器
.addInterceptor(loggingInterceptor)
//写入时间
.writeTimeout(5, TimeUnit.SECONDS)
//连接时间
.connectTimeout(5,TimeUnit.SECONDS)
//读取时间
.readTimeout(5,TimeUnit.SECONDS)
.build();
}
//get请求
public void doGet(String url,final OkHttpCallBack okHttpCallBack){
//创建Request对象
Request build = new Request.Builder()
//请求接口地址
.url(url)
//设置请求方式
.get()
.build();
//开启子线程
okHttpClient.newCall(build).enqueue(new Callback() {
//失败
@Override
public void onFailure(Call call, IOException e) {
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
okHttpCallBack.failure("网络异常");
}
});
}
//成功
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.code()==200){
final String string = response.body().string();
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
okHttpCallBack.Success(string);
}
});
}
}
});
}
public void dopost(String url, HashMap<String,String> params,final OkHttpCallBack callBack){
//拿到body的构建器
FormBody.Builder builder = new FormBody.Builder();
//添加参数,冒号的意思就是逐个读取params.entrySet(),并复制给entry
for(Map.Entry<String,String> map:params.entrySet()){
builder.add(map.getKey(),map.getValue());
}
//拿到requestBody
RequestBody requestBody = builder.build();
//创建request对象
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
//开启子线程
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, Response response) throws IOException {
if(callBack!=null){
if(response.code()==200){
final String result = response.body().string();
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
callBack.Success(result);
}
});
}
}
}
});
}
}
创建LoadModel
import android.os.Handler;
import java.util.HashMap;
import jiaoyibo.bawei.com.zhanshi02.api.UserApi;
import jiaoyibo.bawei.com.zhanshi02.contract.LoadContract;
import jiaoyibo.bawei.com.zhanshi02.net.OkHttpCallBack;
import jiaoyibo.bawei.com.zhanshi02.net.OkHttpUtils;
import jiaoyibo.bawei.com.zhanshi02.net.RequestCallBack;
/**
* <p>文件描述:<p>
* <p>作者:JYB<p>
* <p>创建时间:2019/2/20<p>
* <p>更改时间:2019/2/20<p>
* <p>版本号:1<p>
*/
public class LoadModel implements LoadContract.LloadModel {
//创建handler
private Handler handler = new Handler();
@Override
public void model(HashMap<String, String> map, final RequestCallBack callBack) {
OkHttpUtils.getmInstance().doGet(UserApi.USER_API, new OkHttpCallBack() {
//成功
@Override
public void Success(final String result) {
if(callBack!=null){
handler.post(new Runnable() {
@Override
public void run() {
callBack.Success(result);
}
});
}
}
//失败
@Override
public void failure(final String msg) {
if(callBack!=null){
handler.post(new Runnable() {
@Override
public void run() {
callBack.failure(msg);
}
});
}
}
});
}
}
创建LoadPresenter
import java.util.HashMap;
import jiaoyibo.bawei.com.zhanshi02.contract.LoadContract;
import jiaoyibo.bawei.com.zhanshi02.model.LoadModel;
import jiaoyibo.bawei.com.zhanshi02.net.RequestCallBack;
/**
* <p>文件描述:<p>
* <p>作者:JYB<p>
* <p>创建时间:2019/2/20<p>
* <p>更改时间:2019/2/20<p>
* <p>版本号:1<p>
*/
public class LoadPresenter extends LoadContract.LloadPresenter {
private LoadContract.LloadView lloadView;
private final LoadModel loadModel;
public LoadPresenter(LoadContract.LloadView lloadView) {
this.lloadView = lloadView;
loadModel = new LoadModel();
}
@Override
public void ppresenter(HashMap<String, String> map) {
loadModel.model(map, new RequestCallBack() {
@Override
public void Success(String result) {
if(lloadView!=null){
lloadView.Success(result);
}
}
@Override
public void failure(String msg) {
if(lloadView!=null){
lloadView.failure(msg);
}
}
});
}
//p层解决内存泄漏
public void Destroy(){
lloadView=null;
}
}
创建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.jcodecraeer.xrecyclerview.XRecyclerView;
import java.util.ArrayList;
import java.util.List;
import jiaoyibo.bawei.com.zhanshi02.R;
import jiaoyibo.bawei.com.zhanshi02.bean.UserBean;
/**
* <p>文件描述:<p>
* <p>作者:JYB<p>
* <p>创建时间:2019/2/20<p>
* <p>更改时间:2019/2/20<p>
* <p>版本号:1<p>
*/
public class Adapter extends XRecyclerView.Adapter<Adapter.ViewHolder> {
private Context context;
private List<UserBean.ResultBean> list;
public Adapter(Context context) {
this.context = context;
list = new ArrayList<>();
}
public void setList(List<UserBean.ResultBean> list) {
this.list = list;
notifyDataSetChanged();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view=LayoutInflater.from(context).inflate(R.layout.linear,viewGroup,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
UserBean.ResultBean resultBean = list.get(i);
viewHolder.name.setText(list.get(i).commodityName);
viewHolder.price.setText(list.get(i).price+"");
String [] images = resultBean.masterPic.split("\\|");
Glide.with(context).load(images[0]).into(viewHolder.image);
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView name,price,shou;
public ViewHolder(@NonNull View itemView) {
super(itemView);
image=itemView.findViewById(R.id.image);
name= itemView.findViewById(R.id.name);
price=itemView.findViewById(R.id.price);
shou=itemView.findViewById(R.id.shou);
}
}
}
MainActivity的具体操作
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import java.util.HashMap;
import jiaoyibo.bawei.com.zhanshi02.adapter.Adapter;
import jiaoyibo.bawei.com.zhanshi02.bean.UserBean;
import jiaoyibo.bawei.com.zhanshi02.contract.LoadContract;
import jiaoyibo.bawei.com.zhanshi02.presenter.LoadPresenter;
public class MainActivity extends AppCompatActivity implements LoadContract.LloadView {
private XRecyclerView xrec;
private LoadPresenter loadPresenter;
private Adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
loadPresenter = new LoadPresenter(this);
xrec.setLayoutManager(new GridLayoutManager(this,2));
loadPresenter.ppresenter(new HashMap<String, String>());
}
private void initView() {
xrec = (XRecyclerView)findViewById(R.id.xrec);
}
@Override
public void Success(String result) {
//Gson捷信
UserBean userBean = new Gson().fromJson(result,UserBean.class);
adapter = new Adapter(this);
xrec.setAdapter(adapter);
adapter.setList(userBean.result);
}
@Override
public void failure(String msg) {
}
//解决内存泄漏
@Override
protected void onDestroy() {
super.onDestroy();
if(loadPresenter!=null){
loadPresenter.Destroy();
}
}
}
主页面布局操作
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">
<com.jcodecraeer.xrecyclerview.XRecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/xrec"
></com.jcodecraeer.xrecyclerview.XRecyclerView>
</android.support.constraint.ConstraintLayout>
Adapter布局操作
<?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:layout_margin="20dp"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:id="@+id/image"
android:src="@mipmap/ic_launcher"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/name"
android:text="爱奇艺会员首充99元"
android:textSize="20dp"
android:layout_marginTop="10dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/price"
android:text="¥99.99"
android:textSize="20dp"
android:layout_marginTop="10dp"
android:textColor="#FF0000"
/>
<TextView
android:id="@+id/shou"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:text="以售99件"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>