Utt*_*dam 4 android gridview asynchronous
嗨我是android的新手:
我在GridView中显示图像拇指.为了获得更好的性能,我将异步加载它.
我的AsyncTask如下:
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;
private String image_path;
public BitmapWorkerTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
@Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
Bitmap picture = BitmapFactory.decodeFile(image_path);
int width = picture.getWidth();
int height = picture.getHeight();
float aspectRatio = (float) width / (float) height;
int newWidth = 98;
int newHeight = (int) (98 / aspectRatio);
return picture = Bitmap.createScaledBitmap(picture, newWidth,
newHeight, true);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
public void onDismiss(DialogInterface dialog) {
this.cancel(true);
}
}
Run Code Online (Sandbox Code Playgroud)
和电话表格:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ListRowHolder listRowHolder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.ll_sponsor_list_item,
parent, false);
listRowHolder = new ListRowHolder();
listRowHolder.imgSponsor = (ImageView) convertView
.findViewById(R.id.imggrid_item_image);
convertView.setTag(listRowHolder);
} else {
listRowHolder = (ListRowHolder) convertView.getTag();
}
try {
BitmapWorkerTask task = new BitmapWorkerTask(
listRowHolder.imgSponsor);
task.image_path = ImageName.get(position);
task.execute(1);
} catch (Exception e) {
Toast.makeText(ctx, e + "", Toast.LENGTH_SHORT).show();
}
return convertView;
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是即使我点击后退按钮,任务也在后台运行.
Veg*_*ger 15
使用cancel()停止AsyncTask:
task.cancel(true);
Run Code Online (Sandbox Code Playgroud)
AsyncTask的文档在"取消任务"部分中提供了一些其他详细信息:
可以通过调用cancel(boolean)随时取消任务.调用此方法将导致后续调用isCancelled()返回true.调用此方法后,onCancelled(对象),而不是 onPostExecute(对象)将后调用doInBackground(对象[])的回报.为确保尽快取消任务,应始终定期从doInBackground(Object [])检查isCancelled()的返回值,如果可能的话(例如在循环内).
| 归档时间: |
|
| 查看次数: |
19324 次 |
| 最近记录: |