这个教程将演示如何应用ImageView读取网络图片资源。有两个比较重要的知识点需要特别注意:
Layout 源代码 (XML):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello World, HTTPImage load test" /> <Button id="@+id/get_imagebt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get an image" android:layout_gravity="center" /> <ImageView id="@+id/imview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> </LinearLayout> |
主程序源代码 (Java):
01.
import
java.io.IOException;
02.
import
java.io.InputStream;
03.
import
java.net.HttpURLConnection;
04.
import
java.net.MalformedURLException;
05.
import
java.net.URL;
06.
import
java.util.HashMap;
07.
import
java.util.Map;
08.
import
java.util.Random;
09.
10.
import
android.app.Activity;
11.
import
android.graphics.Bitmap;
12.
import
android.graphics.BitmapFactory;
13.
import
android.os.Bundle;
14.
import
android.util.Log;
15.
import
android.view.View;
16.
import
android.widget.Button;
17.
import
android.widget.EditText;
18.
import
android.widget.ImageView;
19.
20.
public
class
HTTPTest
extends
Activity {
21.
22.
ImageView imView;
23.
String imageUrl=
"http://11.0.6.23/"
;
24.
Random r;
25.
/** Called when the activity is first created. */
26.
@Override
27.
public
void
onCreate(Bundle icicle) {
28.
super
.onCreate(icicle);
29.
setContentView(R.layout.main);
30.
r=
new
Random();
31.
32.
Button bt3= (Button)findViewById(R.id.get_imagebt);
33.
bt3.setOnClickListener(getImgListener);
34.
imView = (ImageView)findViewById(R.id.imview);
35.
}
36.
37.
View.OnClickListener getImgListener =
new
View.OnClickListener()
38.
{
39.
40.
@Override
41.
public
void
onClick(View view) {
42.
// TODO Auto-generated method stub
43.
44.
//i tried to randomize the file download, in my server i put 4 files with name like
45.
//png0.png, png1.png, png2.png so different file is downloaded in button press
46.
int
i =r.nextInt()%
4
;
47.
downloadFile(imageUrl+
"png"
+i+
".png"
);
48.
Log.i(
"im url"
,imageUrl+
"png"
+i+
".png"
);
49.
}
50.
51.
};
52.
53.
Bitmap bmImg;
54.
void
downloadFile(String fileUrl){
55.
URL myFileUrl =
null
;
56.
try
{
57.
myFileUrl=
new
URL(fileUrl);
58.
}
catch
(MalformedURLException e) {
59.
// TODO Auto-generated catch block
60.
e.printStackTrace();
61.
}
62.
try
{
63.
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
64.
conn.setDoInput(
true
);
65.
conn.connect();
66.
int
length = conn.getContentLength();
67.
68.
InputStream is = conn.getInputStream();
69.
70.
bmImg = BitmapFactory.decodeStream(is);
71.
imView.setImageBitmap(bmImg);
72.
}
catch
(IOException e) {
73.
// TODO Auto-generated catch block
74.
e.printStackTrace();
75.
}
76.
}
77.
}