XRecyclerView+Retrofit+RXjava+Fresco请求网络数据
导入的依赖
compile 'com.facebook.fresco:fresco:0.14.1' compile 'com.squareup.retrofit2:retrofit:2.3.0' compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1' compile 'io.reactivex:rxandroid:1.1.0' compile 'com.squareup.okhttp3:okhttp:3.0.0' compile 'com.squareup.okio:okio:1.5.0' compile 'com.squareup.okhttp3:logging-interceptor:3.4.1' compile 'com.squareup.retrofit2:converter-gson:2.3.0' compile 'com.jcodecraeer:xrecyclerview:1.3.2' <uses-permission android:name="android.permission.INTERNET"></uses-permission>
activity_item布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" xmlns:fresco="http://schemas.android.com/apk/res-auto">> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="100dp"> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/myface" android:layout_width="100dp" android:layout_height="100dp" fresco:actualImageScaleType="focusCrop" fresco:placeholderImageScaleType="fitCenter" fresco:progressBarImageScaleType="centerInside" fresco:progressBarAutoRotateInterval="5000" fresco:failureImageScaleType="centerInside" fresco:retryImageScaleType="centerCrop" fresco:fadeDuration="5000" fresco:backgroundImage="@android:color/holo_orange_light" fresco:roundAsCircle="true" > </com.facebook.drawee.view.SimpleDraweeView> <TextView android:id="@+id/mytext" android:layout_width="match_parent" android:layout_height="100dp" android:gravity="center" android:text="世界欢迎你 "/> </LinearLayout> </RelativeLayout>
第一个MainActivity
package com.bawie.www.rikao1206; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import com.bawie.www.rikao1206.adapter.MyAdapter; import com.bawie.www.rikao1206.bean.NewsBean; import com.bawie.www.rikao1206.presenter.ShowPresenter; import com.bawie.www.rikao1206.presenter.ShowPresenterImpl; import com.bawie.www.rikao1206.view.ShowView; import com.jcodecraeer.xrecyclerview.XRecyclerView; import java.util.List; public class MainActivity extends AppCompatActivity implements ShowView{ private XRecyclerView xRecyclerView; private List<NewsBean.NewslistBean> list; private LinearLayoutManager manager; private MyAdapter adapter; private ShowPresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); xRecyclerView = (XRecyclerView) findViewById(R.id.recycler); manager = new LinearLayoutManager(this); manager.setOrientation(LinearLayoutManager.VERTICAL); xRecyclerView.setLayoutManager(manager); //p关联v presenter = new ShowPresenterImpl(this); //p关联m 做网络请求 presenter.relevance(); xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() { @Override public void onRefresh() { adapter.notifyDataSetChanged(); xRecyclerView.refreshComplete();//刷新数据 } @Override public void onLoadMore() { // addData(); // xRecyclerView.loadMoreComplete();//加载数据 } }); } @Override public void showData(NewsBean news) { list = news.getNewslist(); adapter = new MyAdapter(MainActivity.this, list); xRecyclerView.setAdapter(adapter); } /* private void addData() { for (int i = 0; i < 20; i++) { Integer r = Integer.valueOf((int) (Math.random() * 100)); list.add(r, new NewsBean.NewslistBean()); } adapter.notifyDataSetChanged(); }*/ }
MyApp类里
package com.bawie.www.rikao1206; import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; /** */ public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); Fresco.initialize(this); } }
utils包里的RetrofitUtils
package com.bawie.www.rikao1206.utils; import android.util.Log; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by 杨文倩 on 2017/12/6. */ public class RetrofitUtils { private static RetrofitUtils retrofitUtils; private RetrofitUtils() { } public static RetrofitUtils getInstance() { if (retrofitUtils == null) { synchronized (RetrofitUtils.class) { if (retrofitUtils == null) { retrofitUtils = new RetrofitUtils(); } } } return retrofitUtils; } private static Retrofit retrofit; public static synchronized Retrofit getRetrofit(String url) { HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { Log.i("xxx", message); } }); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor) .connectTimeout(500, TimeUnit.SECONDS) .readTimeout(500, TimeUnit.SECONDS) .retryOnConnectionFailure(false) .build(); if (retrofit == null) { retrofit = new Retrofit.Builder().baseUrl(url) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); } return retrofit; } public <T> T getApiService(String url, Class<T> cl) { Retrofit retrofit = getRetrofit(url);//得到retrofit return retrofit.create(cl);//返回的就是网络接口对象 } }
presenter层定义一个接口ShowPresenter
public interface ShowPresenter { void relevance(); }
presenter层定义一个ShowPresenterImpl类
package com.bawie.www.rikao1206.presenter; import com.bawie.www.rikao1206.OnFinishListener; import com.bawie.www.rikao1206.bean.NewsBean; import com.bawie.www.rikao1206.model.ShowModel; import com.bawie.www.rikao1206.model.ShowModelImpl; import com.bawie.www.rikao1206.view.ShowView; public class ShowPresenterImpl implements ShowPresenter,OnFinishListener { ShowView showView; private final ShowModel showModel; //初始化 public ShowPresenterImpl(ShowView showView){ this.showView = showView; //多态 showModel = new ShowModelImpl(); } @Override public void relevance() { //p跟m关联 showModel.getData(this); } @Override public void success(NewsBean news) { showView.showData(news); } }
在Model层定义一个接口ShowModel
package com.bawie.www.rikao1206.model; import com.bawie.www.rikao1206.OnFinishListener; /** * Created by 杨文倩 on 2017/12/6. */ public interface ShowModel { void getData(OnFinishListener listener); }
在model层定义一个类ShowModelImpl
package com.bawie.www.rikao1206.model; import com.bawie.www.rikao1206.OnFinishListener; import com.bawie.www.rikao1206.api.Api; import com.bawie.www.rikao1206.api.ApiService; import com.bawie.www.rikao1206.bean.NewsBean; import com.bawie.www.rikao1206.utils.RetrofitUtils; import rx.Observable; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class ShowModelImpl implements ShowModel { @Override public void getData(final OnFinishListener listener) { ApiService apiService = RetrofitUtils.getInstance().getApiService(Api.api_data, ApiService.class); Observable<NewsBean> observable = apiService.getData(); observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<NewsBean>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(NewsBean bean) { listener.success(bean); } }); } }
在bean包里定义一个NewsBean
package com.bawie.www.rikao1206.bean; import java.util.List; /** * Created by 杨文倩 on 2017/12/6. */ public class NewsBean { /** * code : 200 * msg : success * newslist : [{"ctime":"2016-12-04 13:00","title":"格林:理解科尔吸食大麻 不过我从没吸过","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161204/1-161204120131.jpg","url":"http://www.51tyw.com/nba/2421.html"},{"ctime":"2016-12-04 00:00","title":"三分纪录延续!火箭队连续19场比赛命中10+三分球","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161203/1-161203233J3.jpg","url":"http://www.51tyw.com/nba/2417.html"},{"ctime":"2016-12-04 00:00","title":"詹姆斯谈三连败:是时候紧起来了 必须打得男人点","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161203/1-161203234010.jpg","url":"http://www.51tyw.com/nba/2418.html"},{"ctime":"2016-12-03 12:00","title":"骑士输赢都靠三分?那还要詹姆斯做什么?","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161203/1-161203104344.jpg","url":"http://www.51tyw.com/nba/2407.html"},{"ctime":"2016-12-03 00:00","title":"公牛vs骑士直播看点:詹伟兄弟对决","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161202/1-161202221205.jpg","url":"http://www.51tyw.com/nba/2395.html"},{"ctime":"2016-12-02 22:00","title":"火箭和勇士联手创NBA三分纪录","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161202/1-161202214212.jpg","url":"http://www.51tyw.com/nba/2392.html"},{"ctime":"2016-12-02 22:00","title":"巴克利:勇士打得像女式篮球,太软了!","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161202/1-161202215032.jpg","url":"http://www.51tyw.com/nba/2394.html"},{"ctime":"2016-12-02 20:00","title":"詹姆斯完成月最佳球员4连霸的壮举!","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161202/1-1612021PI0.jpg","url":"http://www.51tyw.com/nba/2388.html"},{"ctime":"2016-12-01 00:00","title":"威少再下三双战书!詹皇会不会先认怂?","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161128/1-16112Q13251.jpg","url":"http://www.51tyw.com/nba/2374.html"},{"ctime":"2016-12-01 00:00","title":"骑士这样的防守想夺冠?也许卫冕只是空谈!","description":"NBA新闻","picUrl":"http://www.51tyw.com/uploads/allimg/161130/1-161130222229.jpg","url":"http://www.51tyw.com/nba/2375.html"}] */ private int code; private String msg; private List<NewslistBean> newslist; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<NewslistBean> getNewslist() { return newslist; } public void setNewslist(List<NewslistBean> newslist) { this.newslist = newslist; } public static class NewslistBean { /** * ctime : 2016-12-04 13:00 * title : 格林:理解科尔吸食大麻 不过我从没吸过 * description : NBA新闻 * picUrl : http://www.51tyw.com/uploads/allimg/161204/1-161204120131.jpg * url : http://www.51tyw.com/nba/2421.html */ private String ctime; private String title; private String description; private String picUrl; private String url; public String getCtime() { return ctime; } public void setCtime(String ctime) { this.ctime = ctime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } }
在api包里定义一个ApiService接口
package com.bawie.www.rikao1206.api; import com.bawie.www.rikao1206.bean.NewsBean; import retrofit2.http.GET; import rx.Observable; /** * Created by 杨文倩 on 2017/12/6. */ public interface ApiService { @GET("nba/?key=71e58b5b2f930eaf1f937407acde08fe&num=10") Observable<NewsBean> getData(); }
在api包里定义一个Api的类
package com.bawie.www.rikao1206.api; /** * Created by 杨文倩 on 2017/12/6. */ public class Api { //http://api.tianapi.com/nba/?key=71e58b5b2f930eaf1f937407acde08fe&num=10 public static final String api_data ="http://api.tianapi.com/"; }
在adapter包里定义MyAdapter类
package com.bawie.www.rikao1206.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.bawie.www.rikao1206.R; import com.bawie.www.rikao1206.bean.NewsBean; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.jcodecraeer.xrecyclerview.XRecyclerView; import java.util.ArrayList; import java.util.List; /** * Created by 杨文倩 on 2017/12/6. */ public class MyAdapter extends XRecyclerView.Adapter<MyAdapter.ViewHolder> { private Context context; private List<NewsBean.NewslistBean> list; public MyAdapter(Context context, List<NewsBean.NewslistBean> list) { this.context = context; this.list = list; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(context, R.layout.activity_item, null); ViewHolder holder = new ViewHolder(view); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { // Glide.with(context).load(list.get(position).getGoods_img()).into(holder.imgLogo); holder.txtName.setText(list.get(position).getTitle()); // DraweeController controller = Fresco.newDraweeControllerBuilder() // .setUri(list.get(position).getPicUrl()) // .setAutoPlayAnimations(true) // .build(); // holder.imgLogo.setController(controller); holder.imgLogo.setImageURI(list.get(position).getPicUrl()); } @Override public int getItemCount() { return list.size(); } public void setData(NewsBean bean){ if(this.list == null){ this.list = new ArrayList<>(); } this.list.addAll(bean.getNewslist()); notifyDataSetChanged(); } class ViewHolder extends RecyclerView.ViewHolder{ private SimpleDraweeView imgLogo; private TextView txtName; public ViewHolder(View itemView) { super(itemView); imgLogo = (SimpleDraweeView) itemView.findViewById(R.id.myface); txtName = (TextView) itemView.findViewById(R.id.mytext); } } }
定义一个OnFinishListener接口
package com.bawie.www.rikao1206; import com.bawie.www.rikao1206.bean.NewsBean; /** * Created by 杨文倩 on 2017/12/6. */ public interface OnFinishListener { void success(NewsBean bean); }
view层理ShowView类
package com.bawie.www.rikao1206.view; import com.bawie.www.rikao1206.bean.NewsBean; /** * Created by 杨文倩 on 2017/12/6. */ public interface ShowView { void showData(NewsBean news); }
接口
http://api.tianapi.com/nba/?key=71e58b5b2f930eaf1f937407acde08fe&num=10