Android ImageView - 从URL加载图像

问题描述:

我有一些“联系”对象,每个都有一个与它们关联的imageURL字符串。我所见过的将图像放入ListView的方式都是将图像手动放入“可绘制”文件夹并调用资源。手动输入图像会破坏此目的。我已经提供了我的getView方法,并且注释掉的线是我感到困惑的。Android ImageView - 从URL加载图像

public View getView(int position, View convertView, ViewGroup parent) { 
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View row = inflater.inflate(R.layout.single_row, parent, false); 
    TextView name = (TextView) row.findViewById(R.id.topLine); 
    TextView phone = (TextView) row.findViewById(R.id.secondLine); 
    ImageView icon = (ImageView) row.findViewById(R.id.icon); 

    name.setText(contactArray.get(position).getName()); 
    phone.setText((CharSequence) contactArray.get(position).getPhone().getWorkPhone()); 
    //icon.setImage from contactArray.get(position).getImageURL(); ???? 

    return row; 
} 

像这样从URL加载图像。

URL url = new URL(contactArray.get(position).getImageURL()); 
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
icon.setImageBitmap(bmp); 

也许如果你正在寻找更全面的方式,并且你有非常大的数据集。我会建议你使用Android-Universal-Image-Loader库。

在使用listView时,您应该异步加载图像,否则您的视图将会冻结并且会出现ANR。以下是可以异步加载图像的完整代码示例。
在您的自定义适配器中创建此类。

class ImageDownloader extends AsyncTask<String, Void, Bitmap> { 
    ImageView bmImage; 

    public ImageDownloader(ImageView bmImage) { 
     this.bmImage = bmImage; 
    } 

    protected Bitmap doInBackground(String... urls) { 
     String url = urls[0]; 
     Bitmap mIcon = null; 
     try { 
     InputStream in = new java.net.URL(url).openStream(); 
     mIcon = BitmapFactory.decodeStream(in); 
     } catch (Exception e) { 
      Log.e("Error", e.getMessage()); 
     } 
     return mIcon; 
    } 

    protected void onPostExecute(Bitmap result) { 
     bmImage.setImageBitmap(result); 
    } 
} 

现在,您可以非常轻松地加载图像,如下所示。

new ImageDownloader(imageView).execute("Image URL will go here"); 

不要忘记添加以下权限到项目的Manifest.xml文件

<uses-permission android:name="android.permission.INTERNET" /> 
+0

这种解决方案简单明了。谢谢,这正是我正在寻找的。 – tryp

+0

我是新手android设备。在哪里把这条线放在mafnifest xml中? –