我想在我的自定义adpater ImageAdapter中使用asynctask来显示手机中的所有图像,因为UI线程上的消息太多了。我尝试使用此代码(现在检索gifview的情况): 适配器:
public ImageAdapter(ArrayList<Media> liste, Context context) {
this.listeImages = liste;
mContext = context;
}
@Override
public int getCount() {
return listeImages.size();
}
@Override
public Object getItem(int position) {
return listeImages.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderPic viewHolder= new ViewHolderPic();
if (convertView == null) {
convertView = lInflater.inflate(R.layout.imagegallery, null);
viewHolder.imageView = (ImageView)
convertView.findViewById(R.id.picGallery);
// viewHolder.gifView = (GifImageView)
convertView.findViewById(R.id.gifG);
convertView.setTag(viewHolder);
} else {
viewHolder =(ViewHolderPic) convertView.getTag();
}
viewHolder.filePic = new
File(listeImages.get(position).getPath());
PopulateGallery populate=new PopulateGallery();
populate.execute(viewHolder);
return convertView;
}
}
AsyncTask:
类PopulateGallery扩展了AsyncTask {
ViewHolderPic viewHolder;
Bitmap bitmap;
@Override
protected Boolean doInBackground(ViewHolderPic... params) {
viewHolder=params[0];
int widhtPic=(screenWidth/3)-6;
// if(!getExtensionFile(viewHolder.filePic).equals("image/gif")) {
// viewHolder.gifView.setVisibility(View.GONE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.ARGB_4444;
options.inDither = true;
bitmap = decodeFile(viewHolder.filePic, widhtPic, (int)
getResources().getDimension(R.dimen.imageGallery_height));
return true;
}
@Override
public void onPostExecute(Boolean result){
viewHolder.imageView.setImageBitmap(bitmap);
}
}
但它一团糟。有空白空间,图像的大小不相同。有时OutOfMemoryError我以前在UI线程中没有。我试着用:
try {
populate.execute(viewHolder).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
但没有结果。我认为这是因为在返回convertView之前任务还没有完成,但问题仍然存在。我该怎么做才能解决这个问题。谢谢。