Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 載入並顯示網路圖片的實作範例

編輯:關於 Android 程式設計

在 Android 中顯示一張來自網路的圖片其實相當容易,核心觀念就是把遠端的圖片下載下來、轉換成 Bitmap,再設定給 ImageView 顯示。以下用一個簡單的例子帶大家實作。

步驟一:建立 Activity 並撰寫下載邏輯

① 建立你的 Activity,本例以 ViewWebImageActivity 說明;
② 在 Activity 中撰寫下載並轉換圖片的程式碼:

復制代碼 代碼如下:String imageUrl = "https://www.jb51.net/images/logo.gif"; //這就是你需要顯示的網絡圖片---網上隨便找的
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 的關鍵。

步驟二:修改版面配置檔

在 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>

步驟三:加上網路權限

最後別忘了在 AndroidManifest.xml 中加上網路存取權限。由於 Android 對權限有嚴格的限制,若沒有宣告 INTERNET 權限,圖片是無法下載並顯示出來的。

希望本文對大家的 Android 開發有所幫助。

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