我有這個ImageAdapter爲Android的ListView控件:爲什麼Android ImageAdapter不能加載圖片?
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
RelativeLayout relativeLayout = null;
Offer currentOffer = mOffersList.get(position);
if (convertView == null) { // create a new view if no recycling
// available
// Make up a new view
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.offer_list_item, null);
relativeLayout = (RelativeLayout) view
.findViewById(R.id.offerImage);
} else {
view = (View) convertView;
relativeLayout = (RelativeLayout) view
.findViewById(R.id.offerImage);
setBackgroundDrawable(relativeLayout, null);
}
String imageUrl = "";
imageUrl = currentOffer.getImageUrl().toString();
Bitmap bitmap = imageCache.get(imageUrl);
if (bitmap != null) {
Drawable dr = new BitmapDrawable(mContext.getResources(), bitmap);
setBackgroundDrawable(relativeLayout, dr);
} else {
if (!downloadingImageUrls.contains(imageUrl)) {
downloadingImageUrls.add(imageUrl);
new DownloadImageAsyncTask().execute(imageUrl);
}
}
return view;
}
這:
class DownloadImageAsyncTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
String imageUrl = params[0];
try {
Bitmap bitmap = BitmapFactory
.decodeStream((InputStream) new URL(imageUrl)
.getContent());
imageCache.put(imageUrl, bitmap);
} catch (IOException e) {
Log.e("DownloadImageAsyncTask", "Error reading bitmap" + e);
}
downloadingImageUrls.remove(imageUrl);
return null;
}
@Override
protected void onPostExecute(Void result) {
notifyDataSetChanged();
}
}
爲什麼所有一起加載列表中的項目?它不是異步的,但不是一個一個。全部一起。
我該如何加載它呢?
爲什麼這個代碼更高效?
// better
public class DownloadImageAsyncTask2 extends
AsyncTask<String, Void, Bitmap> {
private final ImageView imageView;
public DownloadImageAsyncTask2(ImageView imageView) {
this.imageView = imageView;
}
@Override
protected void onPreExecute() {
Log.i("DownloadImageAsyncTask", "Starting image download task...");
}
@Override
protected Bitmap doInBackground(String... params) {
try {
return BitmapFactory.decodeStream((InputStream) new URL(
params[0]).getContent());
} catch (IOException e) {
Log.e("DownloadImageAsyncTask", "Error reading bitmap" + e);
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
}
確保在異步任務中使用WeakReference來訪問ImageView,並檢查ImageView引用是否仍然有效,否則您將持續使用Context引用的時間超過所需時間。另外,如果ImageView已經從窗口中分離出來並被遺忘,那麼調用'setImageBitmap'沒有意義。 – dcow
另外,爲什麼你斷言第二個異步任務比第一個更好,我不一定會認爲它更有效,尤其是如果你在每次ImageView失去一個先前加載的引用時重新加載圖像(即每次配置更改)。 – dcow
哦,我認爲我看到了斷言的性質,第二種方法只會使有問題的視圖無效,並且不要求ListView通過重新創建所有視圖來「重新裝載」所有數據。但是,您可以重寫'notifyDataSetChanged()'來僅執行必要的操作。我相信,默認會重新加載視圖。 – dcow