我正在實現一個列表視圖來顯示DCIM/Camera文件夾下的圖像列表。我在異步列表視圖中加載圖像縮略圖,並在我的AsyncTask實現中使用ImageView的強引用,即ThumbnailReaderTask,此AsyncTask負責加載圖像縮略圖。我被建議使用ImageView的WeakReference。我只是好奇,在這種特殊場景中使用WeakReference會有什麼好處。WeakReference vs Android中的強引用AsyncTask
Java文檔表明
假設垃圾回收器確定在某一時間點,對象是弱可。那時它會原子地清除對該對象的所有弱引用,以及通過一系列強和軟引用可訪問該對象的任何其他弱可訪問對象的所有弱引用。
這是我的代碼(爲了簡單起見,我只是分享我的適配器實現ListView和ThumbnailReaderTask)。
ImageListEntry
//The model class
public class ImageListEntry {
String m_name;
public String getName(){
return m_name;
}
public void setName(String value){
m_name = value;
}
File m_file;
public File getFile(){
return m_file;
}
public void setFile(File value){
m_file = value;
}
}
ImageListAdapter
public class ImageListAdapter extends BaseAdapter {
Activity m_context;
List<ImageListEntry> m_images;
public ImageListAdapter(Activity context, List<ImageListEntry> images){
this.m_context = context;
this.m_images = images;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public Object getItem(int position) {
return m_images.get(position);
}
@Override
public int getCount() {
return m_images.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageListEntry currentImage = m_images.get(position);
TextView nameTextView = (TextView)convertView.findViewById(R.id.explorer_resName);
nameTextView.setText("Set some text...");
ImageView thumbnailImageView = (ImageView)convertView.findViewById(R.id.explorer_resIcon);
//Asynchronous image loading
new ThumbnailReaderTask(thumbnailImageView).execute(currentImage.getFile());
return convertView;
}
}
ThumbnailReaderTask
public class ThumbnailReaderTask extends AsyncTask<File, Void, Bitmap> {
//Should use WeakReference<ImageView>m_imageViewReference
private final ImageView m_imageView;
public ThumbnailReaderTask(ImageView imageView) {
m_imageView = imageView;
}
@Override
protected Bitmap doInBackground(File... params) {
return readBitmapFromFile(params[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
ImageView imageView = m_imageView;//m_imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(R.mipmap.filetype_image);
imageView.setImageDrawable(placeholder);
}
}
}
private Bitmap readBitmapFromFile(File file){
//read thumbnail and return;
}
}
這將有助於清理爲ImageView加載的縮略圖位圖嗎?
您還擁有來自volley的NetworkImageView。很容易與 – peter
@Laser一起使用,這個NetworkImageView對我來說是新的。謝謝! –