Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 載入並顯示網路圖片的實作步驟

編輯:進階開發

Android 自推出以來就獲得不少好評,各家手機廠商也相繼投入這個開放平台。實作上,把網路圖片抓下來顯示在畫面上是非常基礎卻又經常被忽略的一環,本文用一個最小範例拆解整個流程。

Step 1:撰寫 Activity 與下載邏輯

先建立一個 Activity(本例命名為 ViewWebImageActivity),核心是把圖片網址轉成 Bitmap 後塞進 ImageView:

String imageUrl = "https://example.com/photo.jpg";  // 要顯示的網路圖片
Bitmap bmImg;
ImageView imVIEW;
Button button1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    imVIEW = (ImageView) findViewById(R.id.imVIEW);
    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;
}

其中 returnBitMap(String url) 就是負責把網路圖片轉成 Bitmap 的方法,流程為:建立連線、取得輸入串流、交給 BitmapFactory.decodeStream() 解碼。

Step 2:準備版面配置

在 main.xml 中放一個居中的 ImageView 作為顯示容器:

<?XML version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView
        android:id="@+id/imVIEW"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
</LinearLayout>

Step 3:别忘了加上網路權限

Android 對權限控管得相當嚴格。如果沒有宣告網路權限,圖片在模擬器或真機上都不會顯示,只會拿到 null。請在 AndroidManifest.xml 的 </manifest> 之前加入:

<uses-permission android:name="android.permission.INTERNET" />

進階提醒

這個範例把網路 I/O 直接寫在 onCreate() 裡,在單執行緒模型下會阻塞 UI 執行緒,新版 Android 甚至可能直接拋出 NetworkOnMainThreadException。實務上應把下載動作移到背景執行緒(例如 AsyncTask),完成後再回到 UI 執行緒設定圖片,同時加上快取與例外處理,才能避免列表滾動時反覆下載同一張圖。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved