Android 的 ImageView並不支援直接輸入網址並顯示網路圖片
所以要分兩階段來達成
a. 將圖片從網路下載並轉成bmp
b. 將bmp檔顯示出來
以下就介紹最基礎的顯示網路圖片型態
1. 開啟一個新專案, 並在AndroidManifest.xml下, 開啟INTERNET的權限
2. 在layout下新增一個ImageView, 並設定id
這邊以
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
為例
3. 接著介紹目前常用的做法
設定一個methid, 回傳Bitmap的值, 帶入的參數是String型態的網址
並先以null當回傳值, 範例如下:
public static Bitmap getBitmapFromURL(String src) {
return null;
}
4. 接著設定URL來接String型態的網址, 需要import以及try catch, 範例如下:
try {
URL url = new URL(src);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
5. 在來設定連練並執行, 這邊使用的是HttpURLConnection,
然後執行到 connect()時就連線了, 這邊需要IOException的try catch
和之前的try catch可以合併寫在一起, 範例如下:
try {
URL url = new URL(src);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
6. 最後將得到的值, 用BitmapFactory轉成Bitmap檔,
並且在發生exception時, 回傳null, 這樣下載圖片的基礎method就完成了
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream input = conn.getInputStream();
Bitmap mBitmap = BitmapFactory.decodeStream(input);
return mBitmap;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
7. 接著回到onCreate, 由於Android 4.0以上規定, 網路連線以及耗時的工作
必須在其他的thread進行, 所以先寫出一個暱名的thread方法架構並執行
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
}}).start();
8. 然後宣告一個Bitmap 來接網路下載的圖, 而帶的參數是圖片的網址
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Bitmap mBitmap = getBitmapFromURL(http://developer.android.com/images/gp-optimize.png);
}}).start();
9. 完成之後就要將圖片更新到ImageView上了,
這時候又有另一項要注意的, 更新UI必須在UI Thread, 也就是Main Thread上
有很多方法以做到, 這邊就以在開一個runOnUiThread來達成
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
Bitmap mBitmap = getBitmapFromURL("http://developer.android.com/images/gp-optimize.png");
runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
}}
);
}}).start();
10. 接著用setImageBitmap來顯示圖片, 由於要跨thread, 所以要將Bitmap設成final形式
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
final Bitmap mBitmap = getBitmapFromURL("http://developer.android.com/images/gp-optimize.png");
runOnUiThread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
ImageView mImageView = (ImageView) findViewById(R.id.imageView);
mImageView.setImageBitmap(mBitmap);
}}
);
}}).start();
11. 最後執行程式, 就可以看見結果成功從網路顯示圖片了
這篇只是介紹基礎型, 進階的可以在寫用cache來避免短時間重複下同一張圖
然後配合螢幕解析度來在對圖片作顯示大小的調整