我有一个ImageView,我需要做的就是在应用加载时从互联网上显示图像。有一种非常简单的方法吗?
答案 0 :(得分:4)
ImageView.setImageURI
似乎不适用于互联网资源,因此您应该自己阅读位图。
InputStream is = new URL("http://example.com/myimage.jpg").openStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
ImageView iv = (ImageView) findViewById(R.id.myImage);
iv.setImageBitmap(bitmap);
但是这会在UI线程上加载图像,这会导致打嗝。最好在不同的线程中进行,例如使用:
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... params) {
try {
return loadBitmap(params[0]);
} catch (Exception e) {
Log.e("imagetask", "error loading bitmap", e);
return null;
}
}
protected Bitmap loadBitmap(String urlSpec) throws IOException {
InputStream is = new URL(urlSpec).openStream();
try {
return BitmapFactory.decodeStream(is);
} finally {
is.close();
}
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
ImageView iv = (ImageView) findViewById(R.id.myImage);
iv.setImageBitmap(bitmap);
}
}
}.execute("http://example.com/myimage.jpg");
答案 1 :(得分:0)
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet( url);
HttpResponse response = client.execute( get );
Bitmap bitmap = BitmapFactory.decodeStream( response.getEntity().getContent() );