andriod——Retrofit+Fresco+MVP多条目
来源:互联网 发布:继续教育网络培训总结 编辑:程序博客网 时间:2024/05/21 19:35
<uses-permission android:name="android.permission.INTERNET"/>
导入依赖包
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' compile 'com.google.code.gson:gson:2.2.4' compile 'com.facebook.fresco:fresco:0.11.0' compile 'io.reactivex:rxjava:1.0.14' compile 'io.reactivex:rxandroid:1.0.1' compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4' compile 'com.squareup.okhttp3:okhttp:3.9.0' compile 'com.jakewharton:butterknife:8.5.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1' compile 'com.android.support:recyclerview-v7:26.1.0' compile 'com.github.bumptech.glide:glide:3.7.0'}
adapter——NewAdapter
package com.example.xiehaojia_20171204.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.example.xiehaojia_20171204.R;import com.example.xiehaojia_20171204.bean.Bean;import com.facebook.drawee.backends.pipeline.Fresco;import com.facebook.drawee.interfaces.DraweeController;import com.facebook.drawee.view.SimpleDraweeView;public class NewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { Context context; Bean javaBean; public NewAdapter(Context context, Bean javaBean) { this.context = context; this.javaBean = javaBean; } @Override public int getItemViewType(int position) { if (position % 2 == 0) { return 0; } return 1; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == 0) { View view = View.inflate(context, R.layout.item, null); MyHodler myHodler = new MyHodler(view); return myHodler; } else { View view = View.inflate(context, R.layout.item2, null); MyHodler01 myHodler01 = new MyHodler01(view); return myHodler01; } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof MyHodler) { ((MyHodler) holder).tv1.setText(javaBean.getSong_list().get(position).getAuthor()); ((MyHodler) holder).tv2.setText(javaBean.getSong_list().get(position).getAlbum_title()); DraweeController dc = Fresco.newDraweeControllerBuilder() .setUri(javaBean.getSong_list().get(position).getPic_s500()) .setAutoPlayAnimations(true) .build(); ((MyHodler) holder).img.setController(dc); } else { ((MyHodler01) holder).tv1.setText(javaBean.getSong_list().get(position).getAuthor()); ((MyHodler01) holder).tv2.setText(javaBean.getSong_list().get(position).getAlbum_title()); DraweeController dc = Fresco.newDraweeControllerBuilder() .setUri(javaBean.getSong_list().get(position).getPic_s500()) .setAutoPlayAnimations(true) .build(); ((MyHodler01) holder).img.setController(dc); } } @Override public int getItemCount() { return javaBean.getSong_list().size(); } class MyHodler extends RecyclerView.ViewHolder { private final SimpleDraweeView img; private final TextView tv1, tv2; public MyHodler(View itemView) { super(itemView); img = itemView.findViewById(R.id.img); tv1 = itemView.findViewById(R.id.tv1); tv2 = itemView.findViewById(R.id.tv2); } } class MyHodler01 extends RecyclerView.ViewHolder { private final SimpleDraweeView img; private final TextView tv1, tv2; public MyHodler01(View itemView) { super(itemView); img = itemView.findViewById(R.id.img); tv1 = itemView.findViewById(R.id.tv1); tv2 = itemView.findViewById(R.id.tv2); } }}bean——Bean
//http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0model——Imodel
package com.example.xiehaojia_20171204.model;import com.example.xiehaojia_20171204.bean.Bean;import rx.Observer;public interface Imodel { public void shuju(Observer<Bean> observer);}model——Model
package com.example.xiehaojia_20171204.model;import com.example.xiehaojia_20171204.GetRequest_In;import com.example.xiehaojia_20171204.LoggingInterceptor;import com.example.xiehaojia_20171204.bean.Bean;import okhttp3.OkHttpClient;import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit;import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;import retrofit2.converter.gson.GsonConverterFactory;import rx.Observable;import rx.Observer;import rx.Subscriber;import rx.android.schedulers.AndroidSchedulers;import rx.schedulers.Schedulers;public class Model implements Imodel{ private Bean bean; @Override public void shuju(Observer<Bean> observer) { //创建被观察者 Observable.create(new Observable.OnSubscribe<Bean>() { @Override public void call(final Subscriber<? super Bean> subscriber) { //拦截器的使用 OkHttpClient oc=new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build(); //Retrofit的请求数据 Retrofit retrofit=new Retrofit.Builder() //添加拦截器 .client(oc) //设置网络请求的url .baseUrl("http://tingapi.ting.baidu.com/v1/restserver/") //设置Gson .addConverterFactory(GsonConverterFactory.create()) //设置Rxjava .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); //创建网络请求接口的实例 GetRequest_In Request=retrofit.create(GetRequest_In.class); //对发的请求进行封装 Call<Bean> call=Request.getCall(); //使用异步发送网络请求 call.enqueue(new Callback<Bean>(){ //请求成功时回调 @Override public void onResponse(Call<Bean> call, Response<Bean> response) { bean=response.body(); //调用OnNext方法把值传给观察者 subscriber.onNext(bean); subscriber.onCompleted(); } //请求失败时的回调 @Override public void onFailure(Call<Bean> call, Throwable t) { } }); } }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()) .subscribe(observer); }}
presenter——Presenterpackage com.example.xiehaojia_20171204.presenter;import android.content.Context;import com.example.xiehaojia_20171204.bean.Bean;import com.example.xiehaojia_20171204.model.Model;import com.example.xiehaojia_20171204.view.Iview;import rx.Observer;public class Persenter { Context context; Model mm; Iview vv; public Persenter(Context context, Iview vv) { this.context = context; this.vv = vv; mm=new Model(); } public void getData(){ mm.shuju(new Observer<Bean>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } //将bean的值让V层接收 @Override public void onNext(Bean bean) { vv.ShowView(bean); } }); }}
view——Iview
package com.example.xiehaojia_20171204.view;import com.example.xiehaojia_20171204.bean.Bean;public interface Iview { //方法有参bean public void ShowView(Bean bean);}GetRequest_Inpackage com.example.xiehaojia_20171204;import com.example.xiehaojia_20171204.bean.Bean;import retrofit2.Call;import retrofit2.http.GET;public interface GetRequest_In { @GET("ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0") Call<Bean> getCall();}
LoggingInterceptor
package com.example.xiehaojia_20171204;import android.os.Build;import java.io.IOException;import okhttp3.Interceptor;import okhttp3.Request;import okhttp3.Response;public class LoggingInterceptor implements Interceptor { private static final String UA = "User-Agent"; @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request() .newBuilder() .addHeader(UA, makeUA()) .build(); return chain.proceed(request); } private String makeUA() { String s = Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE; return Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE; } }
MainActivity
package com.example.xiehaojia_20171204;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.DividerItemDecoration;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import com.example.xiehaojia_20171204.adapter.NewAdapter;import com.example.xiehaojia_20171204.bean.Bean;import com.example.xiehaojia_20171204.presenter.Persenter;import com.example.xiehaojia_20171204.view.Iview;import com.facebook.drawee.backends.pipeline.Fresco;import butterknife.BindView;import butterknife.ButterKnife;public class MainActivity extends AppCompatActivity implements Iview { @BindView(R.id.rv) RecyclerView rv; private Persenter pp; private NewAdapter newAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Fresco.initialize(this); setContentView(R.layout.activity_main); ButterKnife.bind(this); pp=new Persenter(this,this); pp.getData(); } @Override public void ShowView(Bean bean) { LinearLayoutManager manager=new LinearLayoutManager(this); rv.setLayoutManager(manager); rv.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL)); newAdapter=new NewAdapter(this,bean); rv.setAdapter(newAdapter); }}
OkHttp3Utils
package com.example.xie_20171205;import android.content.Intent;import android.net.Uri;import android.os.Environment;import android.util.Log;import android.widget.Toast;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Map;import java.util.concurrent.TimeUnit;import okhttp3.Cache;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;public class OkHttp3Utils { private static OkHttpClient okHttpClient = null; public OkHttp3Utils() { } public static OkHttpClient getInstance() { if (okHttpClient == null) { //加同步安全 synchronized (OkHttp3Utils.class) { if (okHttpClient == null) { //判空 为空创建实例 // okHttpClient = new OkHttpClient(); // File sdcache = getExternalCacheDir(); File sdcache = new File(Environment.getExternalStorageDirectory(), "cache"); int cacheSize = 10 * 1024 * 1024; okHttpClient = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).cache(new Cache(sdcache.getAbsoluteFile(), cacheSize)).build(); } } } return okHttpClient; } public static void doGet(String url, Callback callback) { //创建OkHttpClient请求对象 OkHttpClient okHttpClient = getInstance(); //创建Request Request request = new Request.Builder().url(url).build(); //得到Call对象 Call call = okHttpClient.newCall(request); //执行异步请求 call.enqueue(callback); } public static void doPost(String url, Map<String, String> params, Callback callback) { //创建OkHttpClient请求对象 OkHttpClient okHttpClient = getInstance(); //3.x版本post请求换成FormBody 封装键值对参数 FormBody.Builder builder = new FormBody.Builder(); //遍历集合 for (String key : params.keySet()) { builder.add(key, params.get(key)); } //创建Request Request request = new Request.Builder().url(url).post(builder.build()).build(); Call call = okHttpClient.newCall(request); call.enqueue(callback); } public static void uploadPic(String url, File file, String fileName) { //创建OkHttpClient请求对象 OkHttpClient okHttpClient = getInstance(); //创建RequestBody 封装file参数 RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file); //创建RequestBody 设置类型等 RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", fileName, fileBody).build(); //创建Request Request request = new Request.Builder().url(url).post(requestBody).build(); //得到Call Call call = okHttpClient.newCall(request); //执行请求 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { //上传成功回调 目前不需要处理 } }); } public static void doPostJson(String url, String jsonParams, Callback callback) { RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams); Request request = new Request.Builder().url(url).post(requestBody).build(); Call call = getInstance().newCall(request); call.enqueue(callback); } public static void download(final MainActivity context, final String url, final String saveDir) { Request request = new Request.Builder().url(url).build(); Call call = getInstance().newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.i("xxx", e.toString()); } @Override public void onResponse(Call call, final Response response) throws IOException { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; try { is = response.body().byteStream(); //apk保存路径 final String fileDir = isExistDir(saveDir); //文件 File file = new File(fileDir, getNameFromUrl(url)); context.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(context, "下载成功:" + fileDir + "," + getNameFromUrl(url), Toast.LENGTH_SHORT).show(); } }); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); //apk下载完成后 调用系统的安装方法 Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); context.startActivity(intent); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) is.close(); if (fos != null) fos.close(); } } }); } public static String isExistDir(String saveDir) throws IOException { // 下载位置 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir); if (!downloadFile.mkdirs()) { downloadFile.createNewFile(); } String savePath = downloadFile.getAbsolutePath(); Log.e("savePath", savePath); return savePath; } return null; } private static String getNameFromUrl(String url) { return url.substring(url.lastIndexOf("/") + 1); }}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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" android:orientation="vertical"> <android.support.v7.widget.RecyclerView android:id="@+id/rv" android:layout_width="match_parent" android:layout_height="match_parent"></android.support.v7.widget.RecyclerView></LinearLayout>
item.xml
<?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="match_parent" xmlns:fresco="http://schemas.android.com/apk/res-auto"> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/img" android:layout_width="100dp" android:layout_height="100dp" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginLeft="20dp" android:layout_marginStart="20dp" fresco:placeholderImage="@mipmap/ic_launcher" fresco:roundAsCircle="true" /> <TextView android:id="@+id/tv1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/tv2" android:layout_alignParentTop="true" android:layout_alignStart="@+id/tv2" android:layout_marginTop="15dp" android:text="26565465465446" android:textColor="#ccc" android:textSize="25dp" /> <TextView android:id="@+id/tv2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tv1" android:layout_marginLeft="31dp" android:layout_marginStart="31dp" android:layout_marginTop="14dp" android:layout_toEndOf="@+id/img" android:layout_toRightOf="@+id/img" android:text="7896546545646" android:textColor="#f00" /> <TextView android:layout_width="match_parent" android:layout_height="2dp" android:layout_alignBottom="@+id/img" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:background="@drawable/fengexian" /></RelativeLayout>
item2.xml
<?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="match_parent" xmlns:fresco="http://schemas.android.com/apk/res-auto"> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/img" android:layout_width="100dp" android:layout_height="100dp" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" fresco:placeholderImage="@mipmap/ic_launcher" /> <TextView android:id="@+id/tv1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginTop="13dp" android:text="26565465465446" android:textColor="#ccc" android:textSize="25dp" /> <TextView android:id="@+id/tv2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/tv1" android:layout_marginTop="15dp" android:text="7896546545646" android:textColor="#f00" /> <TextView android:layout_width="match_parent" android:layout_height="2dp" android:layout_alignBottom="@+id/img" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:background="@drawable/fengexian" android:id="@+id/textView" /></RelativeLayout>
阅读全文
0 0
- andriod——Retrofit+Fresco+MVP多条目
- andriod——Retrofit+Fresco+MVP+Fragment
- andriod——Retrofit+Fresco+MVP网络获取数据
- andriod——Retrofit+Fresco+MVP接口拼接传值
- andriod——Retrofit+Fresco+MVP商品分类
- andriod——Retrofit+Fresco+MVP+RxJAVA列表展示商品点击跳转此详情页面
- andriod——Retrofit+Fresco+MVP+解绑实现购物车
- andriod——Retrofit+Fresco+MVP+解绑实现二级购物车
- andriod——Retrofit+Fresco+MVP+Fragment里添加购物车
- andriod——Retrofit+Fresco+MVP+Fragment判断网络获取数据
- andriod——Retrofit+Fresco+MVP+Fragment自定义动画3秒跳转
- andriod——Fresco+Retrofit+GreenDao
- Retrofit+RxJava+Fresco+MVP
- Retrofit+RxJava+Fresco+MVP
- FrameLayout布局+banner+fresco+recycleView多条目+retrofit请求网络
- MVP+Retrofit+fresco+greendao+eventbus
- MVP+XRexyclerview+RxJava+Retrofit+Fresco
- MVP+Fresco+OKhttp+Retrofit+Recycleview
- 使用代理的爬虫小程序
- CentOS 6.X 安装中文字体
- 基础集合论笔记 目录
- 项目继承ObjectBox在浏览器中查看数据库遇到的坑
- 去除首次进入沉浸模式气泡提示
- andriod——Retrofit+Fresco+MVP多条目
- Robot Framework 学习_1(安装与简介)
- EventBus
- mac常用快捷键
- 屏幕常亮的效果
- 剑指offer 不用加减乘除做加法
- Java HashMap的工作原理
- 算法导论24.1-2,24.1-3,24.1-4
- fatal: remote origin already exists.解决办法