我正在使用回收站查看使用asysnc任務顯示圖像。我正在從Web服務器獲取圖像。我的代碼是Android:如何移動回收站查看圖像請求
從onBindViewHolder梅索德我打電話
new ImageLoadTask(url, holder.imageView).execute();
我ImageLoader的asysnc任務是
public class ImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private String url;
private ImageView imageView;
ProgressDialog pDialog;
public ImageLoadTask(String url, ImageView imageView) {
this.url = url;
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
imageView.setImageBitmap(result);
}
}
問題是,當我滾動並跳過一個或多個視圖被下載的圖像之前和視圖被重新使用,圖像donwnload reqest不會在這些中間視圖上被取消,導致在該視圖中加載實際圖像之前該視圖/這些圖像會一閃而過。
我試着從適配器中傳遞HttpURLConnection
,並檢查它是否爲空,然後在onBindViewHolder
方法上調用disconnect
,但仍然發生。我正在使用
if (holder.urlConnection != null)
{
holder.urlConnection.disconnect();
try {
holder.urlConnection.getInputStream().close();
}
catch (Exception e) {
e.printStackTrace();
}
holder.urlConnection = null;
}
new ImageLoadTask(url, holder.imageView,holder.viewHolderActivity, holder.urlConnection).execute();
如何取消圖像請求?
ImageLoadTask imageLoadTask=new ImageLoadTask(url, holder.imageView);
imageLoadTask.cancel(true);