我有一个带有图像的自定义列表视图。我需要通过 url 设置图像的来源,但我不希望进程阻塞 UI,所以我使用的是 Async 任务。但是,图像仅设置在列表中的一个图像上,并且显示为幻灯片。
有没有更好的方法来解决这个问题?
这是我的代码:
自定义适配器
class MyArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private int i = 0;
Contact[] myContact;
String imageURL;
public MyArrayAdapter(Context context, Contact[] contact) {
super(context, R.layout.custom_list);
this.context = context;
this.myContact = contact;
int s = myContact.length;
int k = contact.length;
}
@Override
public int getCount() {
return myContact.length;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.custom_list, parent, false);
TextView contact_first_name = (TextView) rowView
.findViewById(R.id.first_name);
TextView contact_last_name = (TextView) rowView
.findViewById(R.id.last_name);
imageView = (ImageView) rowView.findViewById(R.id.photo);
imageURL = myContact[i].getImageUrl();
new LoadImageTask().execute(imageURL);
contact_first_name.setText(myContact[i].getFirstName());
contact_last_name.setText(myContact[i].getLastName());
i++;
return rowView;
}
}
异步任务
public class LoadImageTask extends AsyncTask<String, Integer, String> {
Bitmap bitmap;
@Override
protected String doInBackground(String... imageURL) {
// TODO Auto-generated method stub
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String line) {
try {
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}