編輯:Android 開發實例
在 App 裡把網路圖片抓下來放到畫面上,是每個 Android 新手都會遇到的課題。以下從最直白的寫法出發,再逐步加上進度條,讓使用者體驗更完整。
先在版面配置裡擺一個 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:src="@drawable/icon"
android:layout_width="wrap_content"
android:id="@+id/imgPic"
android:layout_gravity="center|center_vertical"
android:layout_height="fill_parent">
</ImageView>
</LinearLayout>
接著在 Activity 中取得遠端圖片並塞進 ImageView:
public class DownloadImage extends Activity {
private ImageView imgPic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_image);
imgPic = (ImageView) findViewById(R.id.imgPic);
String url = "圖片檔案位址";
loadRmoteImage(url);
}
/**
* @param imgUrl 遠端圖片檔案的 URL
* 下載遠端圖片
*/
private void loadRmoteImage(String imgUrl) {
URL fileURL = null;
Bitmap bitmap = null;
try {
fileURL = new URL(imgUrl);
} catch (MalformedURLException err) {
err.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) fileURL
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
int length = (int) conn.getContentLength();
if (length != -1) {
byte[] imgData = new byte[length];
byte[] buffer = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(buffer)) > 0) {
System.arraycopy(buffer, 0, imgData, destPos, readLen);
destPos += readLen;
}
bitmap = BitmapFactory.decodeByteArray(imgData, 0,
imgData.length);
}
} catch (IOException e) {
e.printStackTrace();
}
imgPic.setImageBitmap(bitmap);
}
}
流程很單純:開一條 HttpURLConnection、讀進位元組陣列、用 BitmapFactory.decodeByteArray() 解成 Bitmap,最後 setImageBitmap() 上畫面。別忘了在 AndroidManifest.xml 加上 android.permission.INTERNET 權限。
網路慢或圖片大時,畫面會空白一大片,使用者往往以為程式當掉了。加一條 ProgressBar,讓等待變成看得見的過程,是提升體驗最划算的投資。同時也該把下載丟到子執行緒,避免阻塞主執行緒(UI Thread)而引發 ANR。
public class DownloadImage extends Activity {
private ImageView imgPic;
private ProgressBar progressBar;
private int totalSize = 0;
private int size = 0;
private Handler mHandler;
String url = "https://android.tgbus.com/Android/UploadFiles_4504/201107/20110729103701841.jpg";
private Bitmap bitmap = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_image);
imgPic = (ImageView) findViewById(R.id.imgPic);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setProgress(getProgressInt(progressBar.getMax()));
mHandler = new Handler() {
public void handleMessage(Message msg) {
progressBar.setProgress(getProgressInt(progressBar.getMax()));
if (bitmap != null) {
imgPic.setImageBitmap(bitmap);
}
}
};
new Thread() {
public void run() {
loadRmoteImage(url);
}
}.start();
}
/**
* @param imgUrl 遠端圖片檔案的 URL
* 下載遠端圖片
*/
private void loadRmoteImage(String imgUrl) {
URL fileURL = null;
try {
fileURL = new URL(imgUrl);
} catch (MalformedURLException err) {
err.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) fileURL
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
int length = (int) conn.getContentLength();
totalSize = length;
if (length != -1) {
byte[] imgData = new byte[length];
byte[] buffer = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(buffer)) > 0) {
System.arraycopy(buffer, 0, imgData, destPos, readLen);
destPos += readLen;
size = destPos;
mHandler.sendEmptyMessage(1);
Thread.sleep(100);
}
bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
mHandler.sendEmptyMessage(1);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private int getProgressInt(int max) {
int result = (totalSize > 0) ? (int) (size * max * 1.0 / totalSize) : 0;
return result;
}
}
關鍵改動有三處:下載搬到子 Thread;用 Handler 把進度回傳主執行緒更新 ProgressBar(Android 不允許在子執行緒直接操作 UI);透過 size / totalSize 的比例換算成進度條刻度。
補充提醒:範例中的 Thread.sleep(100) 只是為了讓進度條看起來有層次感,正式專案裡請移除,它會拖慢下載速度。另外 conn.getContentLength() 有時會回傳 -1(伺服器未提供 Content-Length),此時進度條無法運作,需另外設計不確定型態的進度顯示。
用 Handler 實現 ViewPager 廣告頁自動輪播的完整方案
很多電商網站和 App 都有自動輪播的商品推廣圖,看起來體驗很不錯。正好今天在學習 ViewPager,於是就動手做了一個功能類似的 Demo。 下面是其中兩個效果的截圖
Android 登入畫面實作:從輸入欄位到錯誤次數鎖定
這個題目要解決什麼 只要 App 需要帳號,就一定會有一塊登入介面:使用者輸入帳號與密碼,按下按鈕,由程式決定放行或退回。Facebook、微博這類服務是這樣,自家開發的
Android 登入頁面:三機會驗證與按鈕禁用
許多 App 需要登入頁面來保護使用者資料。除了基本的帳號密碼輸入,也可以加入錯誤次數限制,提高安全性。 登入欄位設計 畫面中需要兩個 EditText,一個輸入使用者名
Android 登入功能實作教學
幾乎每一款需要帳號的 App,都少不了一個登入畫面。無論是 Facebook、微博還是自家開發的服務,使用者都得先輸入帳號與密碼,系統驗證通過後才允許進入。本章就帶你從零