Retrofit 是一个 RESTful 的 HTTP 网络请求框架的封装
实现的效果:
接下来就开始------
1.导入依赖:
//tablayout
compile 'com.android.support:design:24.2.1'
// logger日志的使用
compile 'com.orhanobut:logger:2.1.1'
/*xRecyclerview*/
compile 'com.jcodecraeer:xrecyclerview:1.3.2'
// retrofit2
compile 'com.squareup.retrofit2:retrofit:2.0.1'
compile 'com.squareup.retrofit2:converter-gson:2.0.1'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
// imageolader
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
//fresco
compile 'com.facebook.fresco:fresco:0.14.1'
2.添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
3.使用fresco加载图片
必须得在Application中初始化,并在清单文件中注册AndroidManifest.xml
在application内
android:name="view.MyApp"
MyApp
public class MyApp extends Application{
@Override
public void onCreate() {
super.onCreate();
Fresco.initialize(this);//初始化fresco
}
}
4.主页面布局文件activity_main.xml
<?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:id="@+id/activity_main"
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="text.bwie.com.mvphttpdemo1.MainActivity">
<!--xrecyclerview-->
<com.jcodecraeer.xrecyclerview.XRecyclerView
android:id="@+id/xRecyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</com.jcodecraeer.xrecyclerview.XRecyclerView>
</RelativeLayout>
子条目布局:news_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_height="wrap_content">
<com.facebook.drawee.view.SimpleDraweeView
xmlns:fresco="http://schemas.android.com/tools"
android:id="@+id/news_item_img"
android:layout_margin="5dp"
android:layout_width="100dp"
android:layout_height="100dp"
fresco:placeholderImage="@mipmap/ic_launcher"
fresco:placeholderImageScaleType="fitCenter"/>
<TextView
android:layout_marginLeft="10dp"
android:id="@+id/news_item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="标题"
/>
</LinearLayout>
</LinearLayout>
整体文件分包:
5.Api包内:
Api.class
public class Api {
public static final String API_URL="https://api.tianapi.com/";
}
ApiService接口
public interface ApiService {
@GET("/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10&page=0")
rx.Observable<NewsBean> getWXNews();
}
6.view包内:
Iview接口:
public interface Iview {
//得到请求的数据
void getHttpJson(NewsBean newsBean);
}
DividerItemDecoration为Xrecyclerview的添加分割线
public class DividerItemDecoration extends RecyclerView.ItemDecoration{
private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Drawable mDivider;
private int mOrientation;
public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}
public void setOrientation(int orientation) {
if(orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST){
throw new IllegalArgumentException("invalid orientation");
}
mOrientation=orientation;
}
/*划线*/
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
Log.v("main", "onDraw()..");
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
private void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
RecyclerView v = new RecyclerView(parent.getContext());
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
private void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
@Override
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
}
7.model包内:
IModel接口;
public interface IModel {
//请求数据
void getJson(String url);
}
public class HttpModel implements IModel
public class HttpModel implements IModel{
private static final String TAG = "main";
private OnFinish onFinish;
public interface OnFinish{
void OnFinishListener(NewsBean newsBean);
}
public void setOnFinish(OnFinish finish){
this.onFinish=finish;
}
//网络请求
@Override
public void getJson(String url) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
//动态代理得到网络接口
ApiService apiService = retrofit.create(ApiService.class);
Observable<NewsBean> wxNews = apiService.getWXNews();
wxNews.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<NewsBean>() {
@Override
public void onCompleted() {
Log.d(TAG, "onCompleted:============ ");
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "onError:============ ");
}
@Override
public void onNext(NewsBean newsBean) {
Log.d(TAG, "onNext: "+newsBean.getNewslist().get(0).getTitle().toString());
//将值传出去
onFinish.OnFinishListener(newsBean);
}
});
}
}
MyRecyclerAdapter适配器:
public class MyRecyclerAdapter extends XRecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder>{
private Context context;
private NewsBean newsBean;
public MyRecyclerAdapter(Context context, NewsBean newsBean) {
this.context = context;
this.newsBean = newsBean;
}
@Override
public MyRecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.news_item, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
@Override
public void onBindViewHolder(MyRecyclerAdapter.MyViewHolder holder, int position) {
holder.title.setText(newsBean.getNewslist().get(position).getTitle());
//fresco展示图片
Uri uri = Uri.parse(newsBean.getNewslist().get(position).getPicUrl());
holder.img.setImageURI(uri);
}
@Override
public int getItemCount() {
return newsBean.getNewslist().size();
}
public class MyViewHolder extends XRecyclerView.ViewHolder{
public TextView title;
public SimpleDraweeView img;
public MyViewHolder(View itemView) {
super(itemView);
img = (SimpleDraweeView) itemView.findViewById(R.id.news_item_img);
title = (TextView) itemView.findViewById(R.id.news_item_title);
}
}
}
//fresco展示图片
Uri uri = Uri.parse(newsBean.getNewslist().get(position).getPicUrl());
holder.img.setImageURI(uri);
}
@Override
public int getItemCount() {
return newsBean.getNewslist().size();
}
public class MyViewHolder extends XRecyclerView.ViewHolder{
public TextView title;
public SimpleDraweeView img;
public MyViewHolder(View itemView) {
super(itemView);
img = (SimpleDraweeView) itemView.findViewById(R.id.news_item_img);
title = (TextView) itemView.findViewById(R.id.news_item_title);
}
}
}
8.Presenter包内:
HttpPresenter类:
public class HttpPresenter implements HttpModel.OnFinish{
//定义view和model接口的变量
private final Iview iview;
private final HttpModel httpModel;
public HttpPresenter(Iview iview) {
this.iview = iview;
this.httpModel =new HttpModel();
httpModel.setOnFinish(this);
}
public void setNews(String url){
httpModel.getJson(url);
}
//完成网络请求后
@Override
public void OnFinishListener(NewsBean newsBean) {
iview.getHttpJson(newsBean);
}
}
9.最后是MainActivity:
public class MainActivity extends AppCompatActivity implements Iview {
XRecyclerView xRecyclerview;
private MyRecyclerAdapter myRecyclerAdapter;
private HttpPresenter httpPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
xRecyclerview = (XRecyclerView) findViewById(R.id.xRecyclerview);
//线性布局
xRecyclerview.setLayoutManager(new LinearLayoutManager(this));
//添加分割线
xRecyclerview.addItemDecoration(new DividerItemDecoration(MainActivity.this,DividerItemDecoration.VERTICAL_LIST));
httpPresenter = new HttpPresenter(this);
httpPresenter.setNews(Api.API_URL); }
//更新数据
@Override
public void getHttpJson(NewsBean newsBean) {
myRecyclerAdapter = new MyRecyclerAdapter(this, newsBean);
xRecyclerview.setAdapter(myRecyclerAdapter);
}
}
}
完了............