1.MainActivity页面
package com.example.day07_imageloader01;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private NewsAdaper mAdaper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取资源id
listView = findViewById(R.id.listview);
//创建适配器
mAdaper = new NewsAdaper(MainActivity.this);
//赋给listview
listView.setAdapter(mAdaper);
infoData();
}
private String urlStr = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
//获取数据的方法
private void infoData() {
NetUtil.getInstance().getRequest(urlStr, NewsBean.class, new NetUtil.CallBack<NewsBean>() {
@Override
public void onSuccess(NewsBean o) {
mAdaper.setmData(o.getData());
}
});
}
}
2.Bean类
package com.example.day07_imageloader01;
import java.util.List;
public class NewsBean {
private List<DataBean> data;
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String news_id;
private String news_title;
private String news_summary;
private String pic_url;
public String getNews_id() {
return news_id;
}
public void setNews_id(String news_id) {
this.news_id = news_id;
}
public String getNews_title() {
return news_title;
}
public void setNews_title(String news_title) {
this.news_title = news_title;
}
public String getNews_summary() {
return news_summary;
}
public void setNews_summary(String news_summary) {
this.news_summary = news_summary;
}
public String getPic_url() {
return pic_url;
}
public void setPic_url(String pic_url) {
this.pic_url = pic_url;
}
}
}
3.适配器类
package com.example.day07_imageloader01;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import java.util.ArrayList;
import java.util.List;
public class NewsAdaper extends BaseAdapter {
private List<NewsBean.DataBean> mData;
private Context mContext;
public NewsAdaper(Context mContext) {
this.mContext = mContext;
//初始化
mData = new ArrayList<>();
}
public void setmData(List<NewsBean.DataBean> datas){
this.mData = datas;
notifyDataSetChanged();
}
@Override
public int getCount() {
return mData.size();
}
@Override
public NewsBean.DataBean getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
//加载子布局
convertView = LayoutInflater.from(mContext).inflate(R.layout.item,parent,false);
//实例化
holder = new ViewHolder(convertView);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.bind(getItem(position));
return convertView;
}
//创建寄存器
class ViewHolder{
ImageView image;
TextView title;
TextView summary;
//获取资源id
public ViewHolder(View convertView) {
image = convertView.findViewById(R.id.image);
title = convertView.findViewById(R.id.title);
summary = convertView.findViewById(R.id.summary);
//convertView.setTag(this);
}
//赋值
public void bind(NewsBean.DataBean item) {
title.setText(item.getNews_title());
summary.setText(item.getNews_summary());
DisplayImageOptions options = new DisplayImageOptions.Builder()
//配置色彩模式
.bitmapConfig(Bitmap.Config.RGB_565)
//配置是否缓存
.cacheInMemory(true)
.cacheOnDisk(true)
//配置默认显示
.showImageOnLoading(R.mipmap.ic_launcher)
.showImageOnFail(R.mipmap.ic_launcher)
.showImageForEmptyUri(R.mipmap.ic_launcher)
//配置图片如何缩放
.imageScaleType(ImageScaleType.EXACTLY)
//显示圆形
// .displayer(new CircleBitmapDisplayer())
//显示圆角
// .displayer(new RoundedBitmapDisplayer(10))
.displayer(new FadeInBitmapDisplayer(200))
.build();
ImageLoader.getInstance().displayImage(item.getPic_url(),image,options);
}
}
}
4.工具类
package com.example.day07_imageloader01;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class NetUtil {
//单例
private static NetUtil instance;
//私有构造方法
public NetUtil() {
}
//提供方法,获得对象
public static NetUtil getInstance() {
if(instance == null){
instance = new NetUtil();
}
return instance;
}
//执行一个网络请求 返回string
public String getRequest(String urlStr){
String json = "";
try {
//定义url地址
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//设置请求格式
urlConnection.setRequestMethod("GET");
//设置超时
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
//获取状态码
int responseCode = urlConnection.getResponseCode();
if(responseCode == 200){
json = stream2String(urlConnection.getInputStream());
}
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
//将字节流转换为字符流
private String stream2String(InputStream is) throws IOException {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder builder = new StringBuilder();
for (String tmp = br.readLine();tmp != null;tmp = br.readLine()){
builder.append(tmp);
}
return builder.toString();
}
//执行一个网络请求 返回bean
public <E> E getRequest(String urlStr,Class clazz){
String request = getRequest(urlStr);
E e = (E) new Gson().fromJson(request,clazz);
return e;
}
//定义一个接口
public interface CallBack<E>{
void onSuccess(E e);
}
//执行一个网络请求,通过回调返回结果
@SuppressLint("StaticFieldLeak")
public void getRequest(String urlStr, final Class clazz, final CallBack callBack){
new AsyncTask<String,Void,Object>(){
@Override
protected Object doInBackground(String... strings) {
return getRequest(strings[0],clazz);
}
@Override
protected void onPostExecute(Object o) {
callBack.onSuccess(o);
}
}.execute(urlStr);
}
}
5.Application页面初始化加载imageloader
package com.example.day07_imageloader01;
import android.app.Application;
import com.nostra13.universalimageloader.cache.disc.DiskCache;
import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.MemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.io.IOException;
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
//DiskCache
//MemoryCache
//DisplayImageOptions options = new DisplayImageOptions.Builder().build();
ImageLoaderConfiguration configuration = null;
configuration = new ImageLoaderConfiguration.Builder(App.this)
//配置磁盘缓存
//.diskCache(new LruDiskCache(getCacheDir(),new HashCodeFileNameGenerator(),10*1024*1024))
.diskCacheSize(50*1204*1024)
//内存缓存大小
// .memoryCache(new LruMemoryCache(10))
//.memoryCacheSize()
.memoryCacheSizePercentage(10)
//线程配置
// .tasksProcessingOrder()
//默认显示设置
//.defaultDisplayImageOptions(options)
.build();
//初始化imageloder:只有第一次初始化有效果
ImageLoader.getInstance().init(configuration);
}
}
6.AndroidManifest.xml页面
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.day07_imageloader01">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:name=".App"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>