一个很简单的例子,直接上代码:
1. ShowUrlImage.java文件
2.main.xml文件
外加注意权限设定:
1. ShowUrlImage.java文件
package cn.com;
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.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ShowUrlImage extends Activity
{
private Button Image_btn;
private ImageView imageShow;
String uriPic = "http://lh3.ggpht.com/_s354WAuIc9E/"
+ "R_DpW4Rzj-I/AAAAAAAAAsc/Ox73tdxGLSw/logo.jpg";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Image_btn = (Button) findViewById(R.id.Image);
imageShow = (ImageView) findViewById(R.id.imageShow);
Image_btn.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View arg0)
{
/* 设置Bitmap在ImageView中 */
imageShow.setImageBitmap(getURLBitmap());
}
});
}
public Bitmap getURLBitmap()
{
URL imageUrl = null;
Bitmap bitmap = null;
try
{
/* new URL对象将网址传入 */
imageUrl = new URL(uriPic);
} catch (MalformedURLException e)
{
e.printStackTrace();
}
try
{
/* 取得连接 */
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.connect();
/* 取得返回的InputStream */
InputStream is = conn.getInputStream();
// is.read(b)
/* 将InputStream变成Bitmap */
bitmap = BitmapFactory.decodeStream(is);
/* 关闭InputStream */
is.close();
} catch (IOException e)
{
e.printStackTrace();
}
return bitmap;
}
}
2.main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ImageView android:id="@+id/imageShow"
android:layout_below="@+id/myButton1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_gravity="center" />
<Button android:id="@+id/Image" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="image"
android:layout_alignParentBottom="true" />
</RelativeLayout>
外加注意权限设定:
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>