Har*_*M V 2 android android-asynctask custom-adapter
我正在尝试创建一个自定义列表适配器,其中包含需要从Internet下载的每个项目的图像.当我第一次进入活动时 - 应用程序冻结一段时间,直到下载图像,然后加载活动列表.
我可以看出,在活动加载之前正在下载图像.如何在活动加载后下载图像.我想我需要使用Async Task.但由于我在自定义阵列适配器中加载图像,因此不确定如何操作.
这是我的自定义适配器getView():
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.list_item_default, null);
}
Item p = items.get(position);
if (p != null) {
TextView list_title = (TextView) v.findViewById(R.id.list_title);
TextView list_description = (TextView) v
.findViewById(R.id.list_description);
TextView list_timestamp = (TextView) v
.findViewById(R.id.list_timestamp);
ImageView list_image = (ImageView) v.findViewById(R.id.list_image);
if (list_title != null) {
list_title.setText(p.getItemTitle());
}
if (list_description != null) {
list_description.setText(p.getItemDescription());
}
if (list_timestamp != null) {
list_timestamp.setText(p.getItemTimestamp());
}
if (list_image != null) {
Log.d("bMobile", "inside getView() image");
try {
URL imageURL = new URL(p.getItemImage());
HttpURLConnection con = (HttpURLConnection) imageURL
.openConnection();
InputStream inputStrem = con.getInputStream();
Bitmap image = BitmapFactory.decodeStream(inputStrem);
if (null != image)
list_image.setImageBitmap(image);
else
Log.d("bMobile", "Bitmap is Null");
} catch (Exception e) {
}
}
}
return v;
}
Run Code Online (Sandbox Code Playgroud)
的AsyncTask:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
@Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
@Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
private Bitmap download_Image(String url) {
Bitmap bmp =null;
try{
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
}catch(Exception e){}
return bmp;
}
Run Code Online (Sandbox Code Playgroud)
"应用程序冻结" - 这是因为您正在事件线程或UI线程上下载图像.你永远不应该这样做.所有阻塞操作,长时间运行的操作,网络操作都应该在单独的线程上运行.是的,您可以使用asynctask来执行应该解决问题的图像加载.
您可以采取两种方法来解决问题
使用droid fu库中的 WebImageView http://brainflush.wordpress.com/2009/11/23/droid-fu-part-2-webimageview-and-webgalleryadapter/ WebImageView也使用缓存,所以你不需要再次下载图像你已经下载了.下载图像很昂贵并且消耗数据.我使用了WebImageView,并能够在列表中加载图像.我花了大约20分钟才能完成所有工作,所以你知道它很容易集成它.
第二个选项是使用异步任务.请检查Android:使用Asynctask从Web加载图像.stackoverflow中有很多关于如何执行此操作的信息.
你的UI挂起时,你应该有一种令人毛骨悚然的感觉,你在UI线程上做了些什么.
| 归档时间: |
|
| 查看次数: |
5226 次 |
| 最近记录: |