《ImageLoader載入圖片》
ImageLoader載入圖片
1主佈局
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout 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”
tools:context=".MainActivity">
<Button android:id="@+id/left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="url con" app:layout_constraintTop_toTopOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toLeftOf="@id/right"/> <Button android:id="@+id/right" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="client" app:layout_constraintTop_toTopOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintLeft_toRightOf="@id/left"/> <ListView android:id="@+id/news" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@id/left" app:layout_constraintBottom_toBottomOf="parent"/> </android.support.constraint.ConstraintLayout>
2 、 listview子佈局
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
xmlns:app=“http://schemas.android.com/apk/res-auto”>
<ImageView android:id="@+id/imageview" android:layout_width="140dp" android:layout_height="100dp" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> <TextView android:id="@+id/textview1" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="@id/imageview" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toLeftOf="@id/imageview"/> <TextView android:id="@+id/textview2" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="@id/imageview" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toLeftOf="@id/imageview"/> </android.support.constraint.ConstraintLayout>
3//MainActivity主函式
package com.example.imageloader;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;
import com.nostra13.universalimageloader.core.ImageLoader;
public class MainActivity extends AppCompatActivity {
private ListView news;
private MyBaseAdafter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
news = findViewById(R.id.news);
mAdapter = new MyBaseAdafter(this);
news.setAdapter(mAdapter);
findViewById(R.id.left).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//載入資料
NetUtil.getInstance().getRequest("http://api.expoon.com/AppNews/getNewsList/type/1/p/1", Bean.class, new NetUtil.Callbak<Bean>() {
@Override
public void onSuccess(Bean o) {
mAdapter.setListData(o.getData());
}
});
}
});
}
}
4Bean類
package com.example.imageloader;
import java.util.List;
public class Bean {
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_title;
private String news_summary;
private String pic_url;
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;
}
}
}
5 adapter介面卡
package com.example.imageloader;
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.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
import java.util.List;
public class MyBaseAdafter extends BaseAdapter {
private Context context;
private List<Bean.DataBean>mlist;
public MyBaseAdafter(Context context) {
this.context = context;
mlist = new ArrayList<>();
}
public void setListData(List<Bean.DataBean> list){
this.mlist = list;
notifyDataSetChanged();
}
@Override
public int getCount() {
return mlist.size();
}
@Override
public Bean.DataBean getItem(int position) {
return mlist.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHoder viewHoder;
if(convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
viewHoder = new ViewHoder();
viewHoder.textView1 = convertView.findViewById(R.id.textview1);
viewHoder.textView2 = convertView.findViewById(R.id.textview2);
viewHoder.imageView = convertView.findViewById(R.id.imageview);
convertView.setTag(viewHoder);
}else{
viewHoder = (ViewHoder) convertView.getTag();
}
viewHoder.textView1.setText(mlist.get(position).getNews_title());
viewHoder.textView2.setText(mlist.get(position).getNews_summary());
// 1280 * 720 -> 1280 * 720 * 每個畫素佔用位元組數16
//
//RGB_565 red green blue 紅綠藍 的顏色 r佔5byte g佔6byte b佔5byte
//A RGB_4444 A RGB_8888
//ALPHA_8
//BitmapDisplayer
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(8))
.displayer(new FadeInBitmapDisplayer(2000))
.build();
//載入圖片
ImageLoader
.getInstance()
.displayImage(getItem(position).getPic_url(), viewHoder.imageView, options);
//只加載圖片
//回撥返回bitmap
//ImageLoader.getInstance().loadImage();
return convertView;
}
class ViewHoder{
private TextView textView1,textView2;
private ImageView imageView;
}
}
6工具類**
package com.example.imageloader;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.util.LruCache;
import android.widget.ImageView;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetUtil {
//單例
private static NetUtil instance;
//私有構造方法
private NetUtil() {
}
//提供方法,獲取物件
public static NetUtil getInstance() {
if(instance == null) {
instance = new NetUtil();
}
return instance;
}
///////////////////普通get請求
public interface Callbak<T>{
void onSuccess(T t);
}
///執行一個網路請求,通過回撥返回結果
public void getRequest(final String urlStr, final Class clazz, final Callbak callbak) {
new AsyncTask<String, Void, Object>(){
@Override
protected Object doInBackground(String... strings) {
return getRequest(urlStr, clazz);
}
@Override
protected void onPostExecute(Object o) {
callbak.onSuccess(o);
}
}.execute(urlStr);
}
//執行一個網路請求,返回bean
public <T> T getRequest(String urlStr, Class clazz) {
return (T) new Gson().fromJson(getRequest(urlStr), clazz);
}
//執行一個網路請求,返回String結果
public String getRequest(String urlStr) {
String result = "";
try {
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
int responseCode = urlConnection.getResponseCode();
if(responseCode == 200) {
result = stream2String(urlConnection.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private String stream2String(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
for (String tmp = br.readLine(); tmp != null; tmp = br.readLine()) {
sb.append(tmp);
}
return sb.toString();
}
}
初始化介面
//此頁面初始化所有頁面中載入圖片的的格式但是要註冊
package com.example.imageloader;
import android.app.Application;
import android.os.Environment;
import com.nostra13.universalimageloader.cache.disc.DiskCache;
import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
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 com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import java.io.IOException;
//優先於所有頁面(Activity)建立
//主要負責應用全域性初始化
//該物件也是一個context
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
//ctrl + h 檢視累的繼承結構
//MemoryCache
//DiskCache
//FileNameGenerator
//怎麼呼叫api
//要什麼引數
//怎麼給這個引數
//Builder
//構建模式
//鏈式呼叫
//全域性配置
ImageLoaderConfiguration configuration = null;
DisplayImageOptions options = new DisplayImageOptions.Builder()
.build();
//try {
//
configuration = new ImageLoaderConfiguration.Builder(this)
//配置:記憶體 磁碟 快取
//.memoryCache(new LruMemoryCache())
//.memoryCacheSize()
//記憶體快取大小
.memoryCacheSizePercentage(10)
//配置磁碟快取:目錄 檔名生成 大小
//.diskCache(new LruDiskCache(getCacheDir(), new HashCodeFileNameGenerator(), 10*1024*1024))
.diskCacheSize(50*1024*1024)
//執行緒配置
//任務優先順序配置
//FIFO
//載入圖片1 2 3 4 5
//LIFO
//.tasksProcessingOrder(QueueProcessingType.)
//預設顯示配置
//.defaultDisplayImageOptions(options)
.build();
//} catch (IOException e) {
// e.printStackTrace();
//}
//初始化:只有第一次初始化有效果
ImageLoader.getInstance().init(configuration);
//無效果
//ImageLoader.getInstance().init(null);
}
}
在androidMainfest中註冊
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.imageloader">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:name=".App"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
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>
APP全域性配置
@Override
public void onCreate() {
super.onCreate();
//ctrl + h 檢視累的繼承結構
//MemoryCache
//DiskCache
//FileNameGenerator
//怎麼呼叫api
//要什麼引數
//怎麼給這個引數
//Builder
//構建模式
//鏈式呼叫
//全域性配置
ImageLoaderConfiguration configuration = null;
DisplayImageOptions options = new DisplayImageOptions.Builder()
.build();
//try {
//
configuration = new ImageLoaderConfiguration.Builder(this)
//配置:記憶體 磁碟 快取
//.memoryCache(new LruMemoryCache())
//.memoryCacheSize()
//記憶體快取大小
.memoryCacheSizePercentage(10)
//配置磁碟快取:目錄 檔名生成 大小
//.diskCache(new LruDiskCache(getCacheDir(), new HashCodeFileNameGenerator(), 10*1024*1024))
.diskCacheSize(50*1024*1024)
//執行緒配置
//任務優先順序配置
//FIFO
//載入圖片1 2 3 4 5
//LIFO
//.tasksProcessingOrder(QueueProcessingType.)
//預設顯示配置
//.defaultDisplayImageOptions(options)
.build();
//} catch (IOException e) {
// e.printStackTrace();
//}
//初始化:只有第一次初始化有效果
ImageLoader.getInstance().init(configuration);
//無效果
//ImageLoader.getInstance().init(null);
}