OkHttp请求网络数据,并listview展示

OkHTTP使用前步骤:

第一步:导入依赖:
compile 'com.squareup.okio:okio:1.5.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.google.code.gson:gson:2.8.2'

第二部:导入Util工具包:
GsonArrayCallback(封装主线程UI更新并且解析Array类型json串)
NetWorkUtils(判断网络)
OkHttp3Utils(封装网络请求类 doget、dopost)

第三部:清单文件配置网络权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

给大家展示一下4个工具类,这四个工具类的功能有很多,可以供有时间的人学习:
第一个工具类 GsonArrayCallback:
  1. package Utils;  
  2.   
  3. import android.os.Handler;  
  4.   
  5. import com.google.gson.Gson;  
  6. import com.google.gson.JsonArray;  
  7. import com.google.gson.JsonElement;  
  8. import com.google.gson.JsonParser;  
  9.   
  10. import java.io.IOException;  
  11. import java.lang.reflect.ParameterizedType;  
  12. import java.lang.reflect.Type;  
  13. import java.util.ArrayList;  
  14. import java.util.List;  
  15.   
  16. import okhttp3.Call;  
  17. import okhttp3.Callback;  
  18. import okhttp3.Response;  
  19.   
  20. /**  
  21.  * 1. 类的用途 如果要将得到的json直接转化为集合 建议使用该类  
  22.  * 该类的onUi() onFailed()方法运行在主线程  
  23.  * 2. @author forever  
  24.  * 3. @date 2017/9/24 18:47  
  25.  */  
  26.   
  27. public abstract class GsonArrayCallback<T> implements Callback {  
  28.     private Handler handler = OkHttp3Utils.getInstance().getHandler();  
  29.   
  30.     //主线程处理  
  31.     public abstract void onUi(List<T> list);  
  32.   
  33.     //主线程处理  
  34.     public abstract void onFailed(Call call, IOException e);  
  35.   
  36.     //请求失败  
  37.     @Override  
  38.     public void onFailure(final Call call, final IOException e) {  
  39.         handler.post(new Runnable() {  
  40.             @Override  
  41.             public void run() {  
  42.                 onFailed(call, e);  
  43.             }  
  44.         });  
  45.     }  
  46.   
  47.     //请求json 并直接返回集合 主线程处理  
  48.     @Override  
  49.     public void onResponse(Call call, Response response) throws IOException {  
  50.         final List<T> mList = new ArrayList<T>();  
  51.   
  52.         String json = response.body().string();  
  53.         JsonArray array = new JsonParser().parse(json).getAsJsonArray();  
  54.   
  55.         Gson gson = new Gson();  
  56.   
  57.         Class<T> cls = null;  
  58.         Class clz = this.getClass();  
  59.         ParameterizedType type = (ParameterizedType) clz.getGenericSuperclass();  
  60.         Type[] types = type.getActualTypeArguments();  
  61.         cls = (Class<T>) types[0];  
  62.   
  63.         for(final JsonElement elem : array){  
  64.             //循环遍历把对象添加到集合  
  65.             mList.add((T) gson.fromJson(elem, cls));  
  66.         }  
  67.   
  68.             handler.post(new Runnable() {  
  69.                 @Override  
  70.                 public void run() {  
  71.                     onUi(mList);  
  72.   
  73.   
  74.   
  75.                 }  
  76.             });  
  77.   
  78.   
  79.     }  
  80. }  
第二个工具类 GsonObjectCallback:
  1. package Utils;  
  2.   
  3. import android.os.Handler;  
  4.   
  5. import com.google.gson.Gson;  
  6.   
  7. import java.io.IOException;  
  8. import java.lang.reflect.ParameterizedType;  
  9. import java.lang.reflect.Type;  
  10.   
  11. import okhttp3.Call;  
  12. import okhttp3.Callback;  
  13. import okhttp3.Response;  
  14.   
  15. /**  
  16.  * 1. 类的用途 如果要将得到的json直接转化为集合 建议使用该类  
  17.  * 该类的onUi() onFailed()方法运行在主线程  
  18.  * 2. @author forever  
  19.  * 3. @date 2017/9/24 18:47  
  20.  */  
  21.   
  22. public abstract class GsonObjectCallback<T> implements Callback {  
  23.     private Handler handler = OkHttp3Utils.getInstance().getHandler();  
  24.   
  25.   
  26.   
  27.     //主线程处理  
  28.     public abstract void onUi(T t);  
  29.   
  30.     //主线程处理  
  31.     public abstract void onFailed(Call call, IOException e);  
  32.   
  33.     //请求失败  
  34.     @Override  
  35.     public void onFailure(final Call call, final IOException e) {  
  36.         handler.post(new Runnable() {  
  37.             @Override  
  38.             public void run() {  
  39.                 onFailed(call, e);  
  40.             }  
  41.         });  
  42.     }  
  43.   
  44.     //请求json 并直接返回泛型的对象 主线程处理  
  45.     @Override  
  46.     public void onResponse(Call call, Response response) throws IOException {  
  47.         String json = response.body().string();  
  48.         Class<T> cls = null;  
  49.   
  50.         Class clz = this.getClass();  
  51.         ParameterizedType type = (ParameterizedType) clz.getGenericSuperclass();  
  52.         Type[] types = type.getActualTypeArguments();  
  53.         cls = (Class<T>) types[0];  
  54.         Gson gson = new Gson();  
  55.         final T t = gson.fromJson(json, cls);  
  56.         handler.post(new Runnable() {  
  57.             @Override  
  58.             public void run() {  
  59.             onUi(t);  
  60.             }  
  61.         });  
  62.     }  
  63. }  
我们请求的网络数据一般以JSon数据格式为主,而不同的Json数据格式,调用不同的类就可以
第三个工具类: NetWorkUtils,用来判断是否有网络
  1. package Utils;  
  2.   
  3. import android.content.Context;  
  4. import android.net.ConnectivityManager;  
  5. import android.net.NetworkInfo;  
  6.   
  7. /**  
  8.  * 1. 类的用途 联网判断  
  9.  * 2. @author forever  
  10.  * 3. @date 2017/9/8 12:30  
  11.  */  
  12.   
  13. public class NetWorkUtils {  
  14.     //判断网络是否连接  
  15.     public static boolean isNetWorkAvailable(Context context) {  
  16.         //网络连接管理器  
  17.         ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  18.         //网络信息  
  19.         NetworkInfo info = connectivityManager.getActiveNetworkInfo();  
  20.         if (info != null) {  
  21.             return true;  
  22.         }  
  23.   
  24.         return false;  
  25.     }  
  26.   
  27. }  
第四个工具类: OkHttp3Utils,这就是请求网络数据接口了:,这其中包括get请求和post请求
  1. package Utils;  
  2.   
  3. import android.content.Context;  
  4. import android.content.Intent;  
  5. import android.net.Uri;  
  6. import android.os.Environment;  
  7. import android.os.Handler;  
  8. import android.os.Looper;  
  9. import android.util.Log;  
  10. import android.widget.Toast;  
  11.   
  12.   
  13. import java.io.File;  
  14. import java.io.FileOutputStream;  
  15. import java.io.IOException;  
  16. import java.io.InputStream;  
  17. import java.util.Map;  
  18. import java.util.concurrent.TimeUnit;  
  19.   
  20. import app.MyApp;  
  21. import okhttp3.Cache;  
  22. import okhttp3.CacheControl;  
  23. import okhttp3.Call;  
  24. import okhttp3.Callback;  
  25. import okhttp3.FormBody;  
  26. import okhttp3.Interceptor;  
  27. import okhttp3.MediaType;  
  28. import okhttp3.MultipartBody;  
  29. import okhttp3.OkHttpClient;  
  30. import okhttp3.Request;  
  31. import okhttp3.RequestBody;  
  32. import okhttp3.Response;  
  33. import okhttp3.logging.HttpLoggingInterceptor;  
  34.   
  35. /**  
  36.  * 1. 类的用途 封装OkHttp3的工具类 用单例设计模式  
  37.  * 2. @author forever  
  38.  * 3. @date 2017/9/6 09:19  
  39.  */  
  40.   
  41. public class OkHttp3Utils {  
  42.     /**  
  43.      * 懒汉 安全 加同步  
  44.      * 私有的静态成员变量 只声明不创建  
  45.      * 私有的构造方法  
  46.      * 提供返回实例的静态方法  
  47.      */  
  48.   
  49.     private static OkHttp3Utils okHttp3Utils = null;  
  50.   
  51.     private OkHttp3Utils() {  
  52.     }  
  53.   
  54.     public static OkHttp3Utils getInstance() {  
  55.         if (okHttp3Utils == null) {  
  56.             //加同步安全  
  57.             synchronized (OkHttp3Utils.class) {  
  58.                 if (okHttp3Utils == null) {  
  59.                     okHttp3Utils = new OkHttp3Utils();  
  60.                 }  
  61.             }  
  62.   
  63.         }  
  64.   
  65.         return okHttp3Utils;  
  66.     }  
  67.   
  68.     private static OkHttpClient okHttpClient = null;  
  69.   
  70.     public synchronized static OkHttpClient getOkHttpClient() {  
  71.         if (okHttpClient == null) {  
  72.             //判空 为空创建实例  
  73.             // okHttpClient = new OkHttpClient();  
  74. /**  
  75.  * 和OkHttp2.x有区别的是不能通过OkHttpClient直接设置超时时间和缓存了,而是通过OkHttpClient.Builder来设置,  
  76.  * 通过builder配置好OkHttpClient后用builder.build()来返回OkHttpClient,  
  77.  * 所以我们通常不会调用new OkHttpClient()来得到OkHttpClient,而是通过builder.build():  
  78.  */  
  79.             //  File sdcache = getExternalCacheDir();  
  80.             //缓存目录  
  81.             File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");  
  82.             int cacheSize = 10 * 1024 * 1024;  
  83.             //OkHttp3拦截器  
  84.             HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {  
  85.                 @Override  
  86.                 public void log(String message) {  
  87.                     Log.i("xxx", message.toString());  
  88.                 }  
  89.             });  
  90.             //Okhttp3的拦截器日志分类 4种  
  91.             httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);  
  92.   
  93.   
  94.             okHttpClient = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS)  
  95.                     //添加OkHttp3的拦截器  
  96.                     .addInterceptor(httpLoggingInterceptor)  
  97.                     .addNetworkInterceptor(new CacheInterceptor())  
  98.                     .writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS)  
  99.                     .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))  
  100.                     .build();  
  101.         }  
  102.         return okHttpClient;  
  103.     }  
  104.   
  105.     private static Handler mHandler = null;  
  106.   
  107.     public synchronized static Handler getHandler() {  
  108.         if (mHandler == null) {  
  109.             mHandler = new Handler();  
  110.         }  
  111.   
  112.         return mHandler;  
  113.     }  
  114.   
  115.     /**  
  116.      * get请求  
  117.      * 参数1 url  
  118.      * 参数2 回调Callback  
  119.      */  
  120.   
  121.     public static void doGet(String url, Callback callback) {  
  122.   
  123.         //创建OkHttpClient请求对象  
  124.         OkHttpClient okHttpClient = getOkHttpClient();  
  125.         //创建Request  
  126.         Request request = new Request.Builder().url(url).build();  
  127.         //得到Call对象  
  128.         Call call = okHttpClient.newCall(request);  
  129.         //执行异步请求  
  130.         call.enqueue(callback);  
  131.   
  132.   
  133.     }  
  134.   
  135.     /**  
  136.      * post请求  
  137.      * 参数1 url  
  138.      * 参数2 回调Callback  
  139.      */  
  140.   
  141.     public static void doPost(String url, Map<String, String> params, Callback callback) {  
  142.   
  143.         //创建OkHttpClient请求对象  
  144.         OkHttpClient okHttpClient = getOkHttpClient();  
  145.         //3.x版本post请求换成FormBody 封装键值对参数  
  146.   
  147.         FormBody.Builder builder = new FormBody.Builder();  
  148.         //遍历集合  
  149.         for (String key : params.keySet()) {  
  150.             builder.add(key, params.get(key));  
  151.   
  152.         }  
  153.   
  154.   
  155.         //创建Request  
  156.         Request request = new Request.Builder().url(url).post(builder.build()).build();  
  157.   
  158.         Call call = okHttpClient.newCall(request);  
  159.         call.enqueue(callback);  
  160.   
  161.     }  
  162.   
  163.     /**  
  164.      * post请求上传文件  
  165.      * 参数1 url  
  166.      * 参数2 回调Callback  
  167.      */  
  168.     public static void uploadPic(String url, File file, String fileName) {  
  169.         //创建OkHttpClient请求对象  
  170.         OkHttpClient okHttpClient = getOkHttpClient();  
  171.         //创建RequestBody 封装file参数  
  172.         RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);  
  173.         //创建RequestBody 设置类型等  
  174.         RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", fileName, fileBody).build();  
  175.         //创建Request  
  176.         Request request = new Request.Builder().url(url).post(requestBody).build();  
  177.   
  178.         //得到Call  
  179.         Call call = okHttpClient.newCall(request);  
  180.         //执行请求  
  181.         call.enqueue(new Callback() {  
  182.             @Override  
  183.             public void onFailure(Call call, IOException e) {  
  184.   
  185.             }  
  186.   
  187.             @Override  
  188.             public void onResponse(Call call, Response response) throws IOException {  
  189.                 //上传成功回调 目前不需要处理  
  190.             }  
  191.         });  
  192.   
  193.     }  
  194.   
  195.     /**  
  196.      * Post请求发送JSON数据  
  197.      * 参数一:请求Url  
  198.      * 参数二:请求的JSON  
  199.      * 参数三:请求回调  
  200.      */  
  201.     public static void doPostJson(String url, String jsonParams, Callback callback) {  
  202.         RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);  
  203.         Request request = new Request.Builder().url(url).post(requestBody).build();  
  204.         Call call = getOkHttpClient().newCall(request);  
  205.         call.enqueue(callback);  
  206.   
  207.   
  208.     }  
  209.   
  210.     /**  
  211.      * 下载文件 以流的形式把apk写入的指定文件 得到file后进行安装  
  212.      * 参数一:请求Url  
  213.      * 参数二:保存文件的路径名  
  214.      * 参数三:保存文件的文件名  
  215.      */  
  216.     public static void download(final Context context, final String url, final String saveDir) {  
  217.         Request request = new Request.Builder().url(url).build();  
  218.         Call call = getOkHttpClient().newCall(request);  
  219.         call.enqueue(new Callback() {  
  220.             @Override  
  221.             public void onFailure(Call call, IOException e) {  
  222.                 Log.i("xxx", e.toString());  
  223.             }  
  224.   
  225.             @Override  
  226.             public void onResponse(Call call, final Response response) throws IOException {  
  227.   
  228.                 InputStream is = null;  
  229.                 byte[] buf = new byte[2048];  
  230.                 int len = 0;  
  231.                 FileOutputStream fos = null;  
  232.                 try {  
  233.                     is = response.body().byteStream();  
  234.                     //apk保存路径  
  235.                     final String fileDir = isExistDir(saveDir);  
  236.                     //文件  
  237.                     File file = new File(fileDir, getNameFromUrl(url));  
  238.                     fos = new FileOutputStream(file);  
  239.                     while ((len = is.read(buf)) != -1) {  
  240.                         fos.write(buf, 0, len);  
  241.                     }  
  242.                     fos.flush();  
  243.                     //apk下载完成后 调用系统的安装方法  
  244.                     Intent intent = new Intent(Intent.ACTION_VIEW);  
  245.                     intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");  
  246.                     context.startActivity(intent);  
  247.                 } catch (IOException e) {  
  248.                     e.printStackTrace();  
  249.                 } finally {  
  250.                     if (is != null) is.close();  
  251.                     if (fos != null) fos.close();  
  252.   
  253.   
  254.                 }  
  255.             }  
  256.         });  
  257.   
  258.     }  
  259.   
  260.     /**  
  261.      * @param saveDir  
  262.      * @return  
  263.      * @throws IOException 判断下载目录是否存在  
  264.      */  
  265.     public static String isExistDir(String saveDir) throws IOException {  
  266.         // 下载位置  
  267.         if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {  
  268.   
  269.             File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);  
  270.             if (!downloadFile.mkdirs()) {  
  271.                 downloadFile.createNewFile();  
  272.             }  
  273.             String savePath = downloadFile.getAbsolutePath();  
  274.             Log.e("savePath", savePath);  
  275.             return savePath;  
  276.         }  
  277.         return null;  
  278.     }  
  279.   
  280.     /**  
  281.      * @param url  
  282.      * @return 从下载连接中解析出文件名  
  283.      */  
  284.     private static String getNameFromUrl(String url) {  
  285.         return url.substring(url.lastIndexOf("/") + 1);  
  286.     }  
  287.   
  288.     /**  
  289.      * 为okhttp添加缓存,这里是考虑到服务器不支持缓存时,从而让okhttp支持缓存  
  290.      */  
  291.     private static class CacheInterceptor implements Interceptor {  
  292.         @Override  
  293.         public Response intercept(Chain chain) throws IOException {  
  294.             // 有网络时 设置缓存超时时间1个小时  
  295.             int maxAge = 60 * 60;  
  296.             // 无网络时,设置超时为1天  
  297.             int maxStale = 60 * 60 * 24;  
  298.             Request request = chain.request();  
  299.             if (NetWorkUtils.isNetWorkAvailable(MyApp.getInstance())) {  
  300.                 //有网络时只从网络获取  
  301.                 request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();  
  302.             } else {  
  303.                 //无网络时只从缓存中读取  
  304.                 request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();  
  305.                /* Looper.prepare();  
  306.                 Toast.makeText(MyApp.getInstance(), "走拦截器缓存", Toast.LENGTH_SHORT).show();  
  307.                 Looper.loop();*/  
  308.             }  
  309.             Response response = chain.proceed(request);  
  310.             if (NetWorkUtils.isNetWorkAvailable(MyApp.getInstance())) {  
  311.                 response = response.newBuilder()  
  312.                         .removeHeader("Pragma")  
  313.                         .header("Cache-Control", "public, max-age=" + maxAge)  
  314.                         .build();  
  315.             } else {  
  316.                 response = response.newBuilder()  
  317.                         .removeHeader("Pragma")  
  318.                         .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)  
  319.                         .build();  
  320.             }  
  321.             return response;  
  322.         }  
  323.     }  
  324. }  
以上就是四个工具类了。
接下来定义一个自己的类Myapp:作用就好比使用ImageLoader是一样的,不要忘了在清单文件中配置!

  
  
[html] view plain copy
  1. package app;  
  2.   
  3. import android.app.Application;  
  4.   
  5. import com.nostra13.universalimageloader.core.ImageLoader;  
  6. import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;  
  7.   
  8. /**  
  9.  * 1. 类的用途  
  10.  * 2. @author forever  
  11.  * 3. @date 2017/9/8 12:33  
  12.  */  
  13.   
  14. public class MyApp extends Application {  
  15.     public static MyApp mInstance;  
  16.     @Override  
  17.     public void onCreate() {  
  18.         super.onCreate();  
  19.         ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(getApplicationContext());  
  20.         ImageLoader.getInstance().init(configuration);  
  21.         mInstance = this;  
  22.   
  23.     }  
  24.     public static MyApp getInstance() {  
  25.         return mInstance;  
  26.     }  
  27. }  
接下来就是MainActivity了,来请求网络数据,其中get请求成功后的方法是直接调用工具类中的方法,并利用JsonFromat对JSon字符串进行封装一个
类(Users)这个类就不占代码了,直接快捷键就可以了,
  
  
[html] view plain copy
  1. package com.eightgroup.http3text1;  
  2.   
  3. import android.os.Bundle;  
  4. import android.support.v7.app.AppCompatActivity;  
  5. import android.widget.ListView;  
  6. import android.widget.TextView;  
  7. import android.widget.Toast;  
  8.   
  9. import java.io.IOException;  
  10. import java.util.ArrayList;  
  11.   
  12. import Adapter.ListViewBaseAdapter;  
  13. import Bean.MyNews;  
  14. import Bean.Users;  
  15. import Utils.GsonObjectCallback;  
  16. import Utils.NetWorkUtils;  
  17. import Utils.OkHttp3Utils;  
  18. import butterknife.BindView;  
  19. import butterknife.ButterKnife;  
  20. import okhttp3.Call;  
  21.   
  22. public class MainActivity extends AppCompatActivity {  
  23.     String URLPATH = "http://api.tianapi.com/social/?key=71e58b5b2f930eaf1f937407acde08fe&num=20";  
  24.     ListViewBaseAdapter adapter;  
  25.     ArrayList<MyNews> list;  
  26.     @BindView(R.id.listview)  
  27.     ListView listview;  
  28.   
  29.     @Override  
  30.     protected void onCreate(Bundle savedInstanceState) {  
  31.         super.onCreate(savedInstanceState);  
  32.         setContentView(R.layout.activity_main);  
  33.         ButterKnife.bind(this);  
  34.         // 直接类名.方法名,判断网络  
  35.         boolean netWorkAvailable = NetWorkUtils.isNetWorkAvailable(MainActivity.this);  
  36.         if (!netWorkAvailable) {  
  37.             Toast.makeText(MainActivity.this, "连网" + netWorkAvailable, Toast.LENGTH_SHORT).show();  
  38.         }  
  39.         // get请求  
  40.         OkHttp3Utils.getInstance().doGet(URLPATH, new GsonObjectCallback<Users>() {  
  41.             // 请求成功  
  42.             @Override  
  43.             public void onUi(Users users) {  
  44.                 list = new ArrayList<MyNews>();  
  45.                 for (int i = 0; i<users.getNewslist().size(); i++){  
  46.                     list.add(new MyNews(users.getNewslist().get(i).getPicUrl(),users.getNewslist().get(i).getTitle()));  
  47.                 }  
  48.   
  49.                 adapter = new ListViewBaseAdapter(MainActivity.this,list);  
  50.                 listview.setAdapter(adapter);  
  51.                 String text = users.getNewslist().toString();  
  52.             }  
  53.   
  54.             // 请求失败  
  55.             @Override  
  56.             public void onFailed(Call call, IOException e) {  
  57.                 Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();  
  58.             }  
  59.         });  
  60.     }  
  61. }  
要将请求的数据一listview的形式展示出来,就要写适配器了:ListViewAdapter:,这之前我是将要展示的数据单独的有封装了一个类(MyNews),
这个类的代码就不展示了,自己可以根据自己的需求从而添加不同的数据
 
 
  
  
[html] view plain copy
  1. package Adapter;  
  2.   
  3. import android.content.Context;  
  4. import android.content.pm.LabeledIntent;  
  5. import android.view.LayoutInflater;  
  6. import android.view.View;  
  7. import android.view.ViewGroup;  
  8. import android.widget.BaseAdapter;  
  9. import android.widget.ImageView;  
  10. import android.widget.TextView;  
  11.   
  12. import com.eightgroup.http3text1.R;  
  13. import com.nostra13.universalimageloader.core.ImageLoader;  
  14.   
  15. import java.util.ArrayList;  
  16.   
  17. import Bean.MyNews;  
  18. import Bean.Users;  
  19.   
  20. /**  
  21.  * Created by 笔片 on 2017/10/12.  
  22.  */  
  23.   
  24. public class ListViewBaseAdapter extends BaseAdapter{  
  25.     Context context;  
  26.     ArrayList<MyNews> list;  
  27.   
  28.     public ListViewBaseAdapter(Context context, ArrayList<MyNews> list) {  
  29.         this.context = context;  
  30.         this.list = list;  
  31.     }  
  32.   
  33.     @Override  
  34.     public int getCount() {  
  35.         return list == null ? 0 : list.size();  
  36.     }  
  37.   
  38.     @Override  
  39.     public Object getItem(int position) {  
  40.         return list.get(position);  
  41.     }  
  42.   
  43.     @Override  
  44.     public long getItemId(int position) {  
  45.         return position;  
  46.     }  
  47.   
  48.     @Override  
  49.     public View getView(int position, View convertView, ViewGroup parent) {  
  50.         ViewHolder holder;  
  51.         if (convertView == null){  
  52.             convertView = LayoutInflater.from(context).inflate(R.layout.lixtview_item,parent,false);  
  53.             holder = new ViewHolder();  
  54.             holder.title = (TextView) convertView.findViewById(R.id.tv);  
  55.             holder.img = (ImageView) convertView.findViewById(R.id.img);  
  56.             convertView.setTag(holder);  
  57.         }else {  
  58.             holder = (ViewHolder) convertView.getTag();  
  59.         }  
  60.         MyNews myNews = (MyNews) getItem(position);  
  61.         holder.title.setText(myNews.getTitle());  
  62.   
  63.         String imgURL = myNews.getPicURL();  
  64.         ImageLoader instance = ImageLoader.getInstance();  
  65.         instance.displayImage(imgURL,holder.img);  
  66.         return convertView;  
  67.     }  
  68.     static class ViewHolder{  
  69.         TextView title;  
  70.         ImageView img;  
  71.     }  
  72. }  
最后把布局展示一下,很简单的,普通的布局
activity_main.xml:
  
  
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:id="@+id/activity_main"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:paddingBottom="@dimen/activity_vertical_margin"  
  8.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  9.     android:paddingRight="@dimen/activity_horizontal_margin"  
  10.     android:paddingTop="@dimen/activity_vertical_margin"  
  11.     tools:context="com.eightgroup.http3text1.MainActivity">  
  12.   
  13.     <ListView  
  14.         android:id="@+id/listview"  
  15.         android:layout_width="match_parent"  
  16.         android:layout_height="match_parent"></ListView>  
  17. </RelativeLayout>  
listview_item.xml:
  
  
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.   
  6.     <TextView  
  7.         android:id="@+id/tv"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content" />  
  10.     <ImageView  
  11.         android:id="@+id/img"  
  12.         android:layout_width="100dp"  
  13.         android:layout_height="100dp" />  
  14.   
  15. </LinearLayout>  
好了,以上就是全部的代码了,由于我选的网络借口不是很好,所以,展示出来的第一印象不是很好,但是总体的效果是实现了,
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值