編輯:關於 Android 程式設計
在 ListView 中載入圖片是非常常見的場景,一個好的圖片載入器必須滿足幾個要求:
(1)無論圖片來自網路還是本地,都應該非同步載入,例如使用 AsyncTask。
(2)為了避免重複下載並提升頁面顯示速度,通常要做快取,最常見的就是 LruCache。
(3)為了提升 ListView 效能,一般會用 holder 重用 item。
基本結構大致如下:
public class MainActivity extends Activity {
private ImageLoader imageLoader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageLoader = new ImageLoader(new ImageDownloader(){
@Override
public Bitmap download(String path, int width, int height) {
return HttpUtil.download(path);
}
});
final ListView listview = (ListView) this.findViewById(R.id.listview);
Button btn = (Button) this.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<ItemBean> dataList = getDataList();
listview.setAdapter(new ListViewAdapter(MainActivity.this, dataList));
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
imageLoader.destory();
}
private class ListViewAdapter extends BaseAdapter {
private Context context;
private List<ItemBean> dataList;
public ListViewAdapter(Context context, List<ItemBean> dataList){
this.context = context;
this.dataList = dataList;
}
@Override public int getCount() { return dataList.size(); }
@Override public Object getItem(int position) { return dataList.get(position); }
@Override public long getItemId(int position) { return position; }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = null;
if (convertView == null) {
holder = new Holder();
convertView = new ItemView(context);
holder.itemView = (ItemView) convertView;
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
ItemView itemView = holder.itemView;
ImageView itemImageView = itemView.getImageView();
ItemBean item = dataList.get(position);
// 先設定一張預設圖片,避免復用時顯示錯誤的圖
itemImageView.setImageResource(R.drawable.ic_launcher);
// 再非同步載入實際圖片
imageLoader.loadImage(item.getImagePath(), 50, 50, itemImageView);
return itemView;
}
class Holder { ItemView itemView; }
}
}
問題就在這裡:假設下載一張圖要 10 秒,每頁顯示 3 個 item。使用者打開第一頁時顯示 item0、item1、item2,在 item0 還沒下載完時就滑到第三頁(item6、item7、item8)。由於 item 是被復用的,此時若 item6 復用了 item0 的 View,當 item0 下載完成後,item6 上就會錯誤地顯示 item0 的圖片,畫面一片混亂。使用者滑動越快,錯亂越嚴重。
下面這個載入器就能避免這個問題(出自一位同事之手,寫得很棒)。它的核心關鍵是:用 WeakHashMap 記錄每個 ImageView 當前對應的圖片路徑,在下載完成回填時比對 ImageView 現在對應的 key 是否還是最初那個,只有一致才顯示,這樣被復用的 ImageView 就不會顯示錯誤圖片:
public class ImageLoader {
private static final String TAG = "ImageLoader";
private ImageCache cache;
private HashSet<String> cacheKeys = new HashSet<String>();
private ImageDownloader downloader;
// 保存 filepath 和 ImageView 的關係,因為 ImageView 會復用,只有這個關係才是正確的
private WeakHashMap<ImageView, String> imageView2FileMap = new WeakHashMap<ImageView, String>();
// 一個 filepath 可能對應多個 ImageView
private HashMap<String, HashSet<ImageViewReference>> file2ImageViewMap = new HashMap<String, HashSet<ImageViewReference>>();
// 正在讀的或已在佇列中的 filepath,讀完刪除
private HashSet<String> fileInLoadSet = new HashSet<String>();
public ImageLoader(ImageDownloader downloader) {
if (downloader == null) {
throw new RuntimeException("ImageDownloader can not be null");
}
this.cache = ImageCache.getInstance();
this.downloader = downloader;
}
/**
* 給 ImageView 設定圖片。
* @return 快取中有則直接設定並回傳 true;沒有則非同步讀取,讀完再設定,回傳 false
*/
public boolean loadImage(String filePath, int width, int height, ImageView imageView) {
String filePathKey = getKeyForFilePath(filePath, width, height);
Bitmap bmp = cache.get(filePathKey);
if (bmp == null) {
ImageViewReference imageViewRef = new ImageViewReference(imageView);
// 更新 ImageView 和 filepath 的最新關係
imageView2FileMap.put(imageView, filePathKey);
HashSet<ImageViewReference> imageViewSet = file2ImageViewMap.get(filePathKey);
if (imageViewSet == null) {
imageViewSet = new HashSet<ImageViewReference>();
file2ImageViewMap.put(filePathKey, imageViewSet);
}
imageViewSet.add(imageViewRef);
// 不會重複下載
if (fileInLoadSet.contains(filePathKey)) {
return false;
} else {
fileInLoadSet.add(filePathKey);
}
Holder holder = new Holder();
holder.width = width;
holder.height = height;
holder.filePath = filePath;
holder.filePathKey = filePathKey;
holder.imageViewRef = imageViewRef;
new ImageLoadTask().execute(holder);
return false;
} else {
imageView.setImageBitmap(bmp);
return true;
}
}
private class ImageLoadTask extends AsyncTask<Holder, Void, Holder> {
@Override
protected Holder doInBackground(Holder... params) {
Holder holder = params[0];
int width = holder.width;
int height = holder.height;
String filePath = holder.filePath;
String filePathKey = holder.filePathKey;
// 找到 key 對應的所有 ImageView,數量為 0 說明不用下載了
int count = getCountOfImageViewForKey(filePathKey);
if (count <= 0) {
return null;
}
try {
Random rnd = new Random();
Thread.sleep((int) (1000 * rnd.nextDouble()));
} catch (Exception e) {
e.printStackTrace();
}
// 開始讀取並放入 cache
if (downloader != null) {
Bitmap bmp = downloader.download(filePath, width, height);
if (bmp != null) {
cache.put(filePathKey, bmp);
cacheKeys.add(filePath);
holder.imageData = bmp;
}
}
return holder;
}
@Override
protected void onPostExecute(Holder holder) {
super.onPostExecute(holder);
String filePathKey = holder.filePathKey;
fileInLoadSet.remove(filePathKey);
Bitmap data = holder.imageData;
if (data == null) {
return;
}
ArrayList<ImageView> imageViewArrayList = getImageViewListForKey(filePathKey);
if (imageViewArrayList.size() == 0) {
return;
}
// 遍歷 ImageView 列表,比對該 ImageView 對應的最新 key 是否為剛下載好的 key
// 只有一致才顯示;不一致說明該 ImageView 已被復用,對應到了新的 key
for (ImageView imageView : imageViewArrayList) {
String latestFilePathKey = imageView2FileMap.get(imageView);
if (latestFilePathKey != null && latestFilePathKey.equals(filePathKey)) {
if (imageView != null) {
imageView.setImageBitmap(data);
Log.e(TAG, "設置圖片 ");
}
// 即使不 remove,也會自動回收
imageView2FileMap.remove(imageView);
}
}
file2ImageViewMap.remove(filePathKey);
}
}
class Holder {
int width, height;
String filePath, filePathKey;
Bitmap imageData;
ImageViewReference imageViewRef;
}
private String getKeyForFilePath(String imagePath, int width, int height) {
return imagePath + "_" + width + "_" + height;
}
public void clear() {
imageView2FileMap.clear();
file2ImageViewMap.clear();
fileInLoadSet.clear();
for (String cacheKey : cacheKeys) {
cache.remove(cacheKey);
}
cacheKeys.clear();
}
public void destory() {
clear();
ImageCache.destroy();
}
public interface ImageDownloader {
public Bitmap download(String path, int width, int height);
}
private ArrayList<ImageView> getImageViewListForKey(String filePathKey) {
ArrayList<ImageView> imageViewArrayList = new ArrayList<ImageView>();
HashSet<ImageViewReference> imageViewReferences = file2ImageViewMap.get(filePathKey);
if (imageViewReferences == null) {
return null;
}
Iterator<ImageViewReference> it = imageViewReferences.iterator();
while (it.hasNext()) {
ImageViewReference reference = it.next();
if (reference.get() != null) {
imageViewArrayList.add(reference.get());
} else {
it.remove();
}
}
return imageViewArrayList;
}
private int getCountOfImageViewForKey(String filePathKey) {
ArrayList<ImageView> imageViewArrayList = getImageViewListForKey(filePathKey);
if (imageViewArrayList == null) {
return 0;
} else {
return imageViewArrayList.size();
}
}
private static class ImageCache extends LruCache<String, Bitmap> {
private static final int cacheSize = 10 * 1024 * 1024;
private static ImageCache instance = new ImageCache(cacheSize);
public static ImageCache getInstance() { return instance; }
private ImageCache(int maxSize) { super(maxSize); }
@Override protected int sizeOf(String key, Bitmap value) { return value.getByteCount(); }
public static void destroy() {
if (instance == null) return;
instance.evictAll();
instance = null;
}
}
private static class ImageViewReference extends WeakReference<ImageView> {
public ImageViewReference(ImageView r) { super(r); }
@Override public boolean equals(Object o) {
ImageViewReference other = (ImageViewReference) o;
return this.get() == other.get();
}
@Override public int hashCode() {
ImageView imageView = this.get();
if (imageView != null) return imageView.hashCode();
return 0;
}
}
}
源碼在此:https://download.csdn.net/download/goldenfish1919/7320823
深度學習入門:從人工神經網路(ANN)理解卷積神經網路(CNN)的本質
背景 先前在網路上搜過大量關於 CNN、卷積神經網路(Convolutional Neural Network)的文章,多數都在講如何卷積、卷積層如何操作、具體怎麼計算、
Android 側滑導覽選單實作(下):跟進 Material Design 的 NavigationView 標準做法
上一篇我們快速堆砌了幾種側滑導覽選單的效果,這一篇則要來探討「當下」該如何依照 Android 官方設計規範來打造側滑選單。之所以強調「當下」,是因為這套設計標準並非一成
Unity3d 接入 Android SDK 解析(一):Unity 與 Android 的互相調用
一、前言 論學習心態 每當進入一個新的工作環境、處於一種新的領域時,人總是會變得急功近利,特別是當任務緊急時,總想著不斷地從網上搜尋答案、不斷地去尋問他人,十足的拿來主
Adapter 中 EditText、CheckBox 狀態記住方案(二):內容保存與錯位修正
上一篇已經解決了 Adapter 中 CheckBox 記住狀態、EditText 可編輯的問題,這次則要進一步處理:如何記住 EditText 的內容,以及在點擊加減