首先在AndroidManifest.xml中给程序加上访问Internet的权限:
<uses-permissionandroid:name="android.permission.INTERNET" />
然后在布局文件中加入一个ImageView,用来显示网络上的图片:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView" />
</LinearLayout>
在主程序的Activity中写从网络中得到图片,并转化成InputStream,然后再转化成可以显示在ImageView里的Bitmap。
package com.image;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class NetImageActivity extends Activity {
/** Called when the activity is first created. */
String imageUrl = "http://content.52pk.com/files/100623/2230_102437_1_lit.jpg";
Bitmap bmImg;
ImageView imView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imView = (ImageView) findViewById(R.id.imageView);
imView.setImageBitmap(returnBitMap(imageUrl));
}
public Bitmap returnBitMap(String url){
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}