編輯:Android 開發實例
本文是一位 Android 開發愛好者分享的小人時鐘實作範例,作者也一併記錄了自己從入門到動手的過程,與同樣在學習路上的朋友共勉。以下是改寫後的內容。
我開始關注 Android,其實也不過大約一年前的事。可那時在裝開發環境時就栽了跟頭,怎麼弄都裝不成功,無奈之下只好作罷。今年五一放假在家,抱著試試看的心態重拾 Android,沒想到環境安裝得意外順利,這一下就把一年前的熱情重新點燃了。於是趁熱打鐵,一邊找來幾本 Android 入門電子書猛啃,一邊照葫蘆畫瓢開始動手。
幾番嘗試下來,算是摸著點門道。剛好公司有位同事是個安卓控,在網上看到一款小人時鐘的網頁程式(如下截圖),覺得非常有趣,可是翻遍應用市場卻找不到能下載的版本,於是便鼓動我自己做一個。說實話,我那時也才剛踏上 Android 開發的漫漫長路,經驗實在有限,但初生牛犢不怕虎,說幹就幹。

老實說,這個範例對 Android 高手們而言實在不值一哂。它與其說是寫給廣大菜鳥看的,倒不如說是寫給歲月的一曲離歌——若干年後,就讓我們在記憶的塵埃裡,去尋找那消逝但美麗的青春。
我的開發環境是 Eclipse Classic 3.7.2 + Android SDK 2.3.3,具體安裝過程網上一搜一大堆,這裡就不多說了。
首先打開 Eclipse,新增一個專案,命名為 LittlePersonClock。(Eclipse 怎麼建專案、加檔案等操作,這裡也不再贅述。)
接著把小人時鐘的 0 到 9 這十個數字,以及「:」這個分隔符號,各自擷圖並裁切成合適尺寸(依解析度而定),如下圖所示,分別命名為 colon.png、n0.png……n9.png。然後在專案的 res 底下新增一個 drawable 資料夾,把這 11 張圖片放進去。

這個做法的巧思在於:用圖片代替文字來顯示數字。時、分、秒各需要兩個位數,加上兩個冒號,一共就是 8 個 ImageView。時鐘運作時,只需要按當下的時間換掉每個 ImageView 的 image resource 即可,不必去處理字型與畫布繪製。
接著在 main.xml 中採用相對佈局(RelativeLayout),放入 8 個 ImageView 與一個 Button:
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#FFFFFFFF">
<ImageView
android:id="@+id/iHourHigh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/iHourLow"
android:layout_marginTop="100dip"
android:layout_marginLeft="10dip"
android:src="@drawable/n0" >
</ImageView>
<ImageView
android:id="@+id/iHourLow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/tColonHM"
android:layout_marginLeft="1dip"
android:layout_marginTop="100dip"
android:layout_toRightOf="@id/iHourHigh"
android:src="@drawable/n1" >
</ImageView>
<ImageView
android:id="@+id/tColonHM"
android:layout_marginTop="100dip"
android:src="@drawable/colon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/iHourLow"
android:layout_marginLeft="1dip"/>
<ImageView
android:id="@+id/iMinuteHigh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btnReturn"
android:layout_marginLeft="1dip"
android:layout_marginTop="100dip"
android:layout_toRightOf="@id/tColonHM"
android:src="@drawable/n2" >
</ImageView>
<ImageView
android:id="@+id/iMinuteLow"
android:src="@drawable/n3"
android:layout_marginTop="100dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/iMinuteHigh"
android:layout_marginLeft="1dip">
</ImageView>
<ImageView
android:id="@+id/tColonMS"
android:layout_marginTop="100dip"
android:src="@drawable/colon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/iMinuteLow"
android:layout_marginLeft="1dip"/>
<ImageView
android:id="@+id/iSecondHigh"
android:src="@drawable/n5"
android:layout_marginTop="100dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/tColonMS"
android:layout_marginLeft="1dip">
</ImageView>
<ImageView
android:id="@+id/iSecondLow"
android:src="@drawable/n6"
android:layout_marginTop="100dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/iSecondHigh"
android:layout_marginLeft="1dip">
</ImageView>
<Button
android:id="@+id/btnExit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tColonMS"
android:text="退出"
android:layout_marginTop="50dip"
android:layout_marginLeft="100dip"
android:textSize="20dp"/>
</RelativeLayout>
這裡有個值得留意的細節:XML 裡用 @+id/ 與 @id/ 兩種寫法。+ 代表「順便幫我建立這個 id」,而沒有 + 則是「引用一個已存在的 id」。因為 ImageView 之間要互相參照位置,先宣告的那一個用 @+id/ 建立,後面引用的就可以省掉加號。
然後在 LittlePersonClock.java 中實作具體邏輯:
package com.littlepersonclock.kernel;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class LittlePersonClock extends Activity {
private ImageView ivhh = null, ivhl = null;
private ImageView ivmh = null, ivml = null;
private ImageView ivsh = null, ivsl = null;
private Button btnExit = null;
private Timer timer = new Timer();
int i = 0, hour, minute, second;
Calendar c = null;
int amorpm = 0;
// 十個數字圖資對應表,索引 0~9
final int did[] = {
R.drawable.n0, R.drawable.n1, R.drawable.n2, R.drawable.n3, R.drawable.n4,
R.drawable.n5, R.drawable.n6, R.drawable.n7, R.drawable.n8, R.drawable.n9
};
// 實際用法應該配合 Handler 來實現 timer 功能,這跟 Android 的執行緒安全有關
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
c = Calendar.getInstance();
amorpm = c.get(Calendar.AM_PM);
hour = c.get(Calendar.HOUR);
if (amorpm == Calendar.PM)
hour += 12;
minute = c.get(Calendar.MINUTE);
second = c.get(Calendar.SECOND);
// 十位數用整除、個位數取餘數,拆出每個位數
ivhh.setImageResource(did[(int) (hour / 10)]);
ivhl.setImageResource(did[hour % 10]);
ivmh.setImageResource(did[(int) (minute / 10)]);
ivml.setImageResource(did[minute % 10]);
ivsh.setImageResource(did[(int) (second / 10)]);
ivsl.setImageResource(did[second % 10]);
break;
}
super.handleMessage(msg);
}
};
TimerTask task = new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
protected void onDestroy() {
if (timer != null) {
timer.cancel();
timer = null;
}
super.onDestroy();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivhh = (ImageView) findViewById(R.id.iHourHigh);
ivhl = (ImageView) findViewById(R.id.iHourLow);
ivmh = (ImageView) findViewById(R.id.iMinuteHigh);
ivml = (ImageView) findViewById(R.id.iMinuteLow);
ivsh = (ImageView) findViewById(R.id.iSecondHigh);
ivsl = (ImageView) findViewById(R.id.iSecondLow);
// 先畫一次當前時間,避免啟動瞬間畫面空白
c = Calendar.getInstance();
amorpm = c.get(Calendar.AM_PM);
hour = c.get(Calendar.HOUR);
if (amorpm == Calendar.PM)
hour += 12;
minute = c.get(Calendar.MINUTE);
second = c.get(Calendar.SECOND);
ivhh.setImageResource(did[(int) (hour / 10)]);
ivhl.setImageResource(did[hour % 10]);
ivmh.setImageResource(did[(int) (minute / 10)]);
ivml.setImageResource(did[minute % 10]);
ivsh.setImageResource(did[(int) (second / 10)]);
ivsl.setImageResource(did[second % 10]);
// 啟動後等 1 秒,之後每 1 秒觸發一次
timer.schedule(task, 1000, 1000);
btnExit = (Button) findViewById(R.id.btnExit);
btnExit.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
LittlePersonClock.this.onDestroy();
}
});
}
}
幾個值得拆解的重點:
位數拆分。核心邏輯其實只有兩行:十位數用 (int)(value / 10)、個位數用 value % 10,再拿這兩個數字去索引 did[] 陣列換成對應的圖片資源。整個時鐘的「顯示」就靠這招完成。
12 與 24 小時制的轉換。範例用 Calendar.HOUR(12 小時制)取值,再判斷 AM_PM 是否為 PM 來加 12。其實直接改用 Calendar.HOUR_OF_DAY 就能拿到 24 小時制,可以省掉這段判斷。
Tween 執行緒 + Handler。Timer 的背景執行緒只負責發送 Message,真正去動 ImageView 的是主執行緒的 handler。作者也在註解裡點明了原因:這跟 Android 的執行緒安全有關。這個模式在我們前面幾篇裡已經看過好幾次了。
資源釋放。onDestroy() 裡呼叫 timer.cancel() 是必要的收尾,否則 Activity 被銷毀後,Timer 仍會持續每秒發送 Message,造成不必要的耗電與記憶體洩漏。
編譯後打開模擬器,測試起來還算堪用,以下是截圖(靜態圖看不出跳動的動態感):

受限於水平與經驗,這個範例肯定還有許多不完善之處。作者自己也說,他一向懶於動筆、疏於總結,文章寫得只能點到為止——要是看不懂,實在不是你的錯。
不過若真要拿來當成產品,有幾個地方值得再打磨:其一,每秒都去 setImageResource 六次,其中大部分其實沒變(例如時位一小時才動一次),可以只在位數真的改變時才更新,省下不必要的解碼與配置。其二,圖片應該依螢幕密度準備多套資源,否則在不同解析度的裝置上會被放大得模糊。其三,退出按鈕直接呼叫 onDestroy() 並不是好做法——生命周期方法應該交給系統呼叫,這裡改成 finish() 才是正確語意。
這些正好說明了寫程式的樂趣:先讓它動起來,再想辦法讓它動得漂亮。
Android 登入應用教學:三次嘗試後停用登入按鈕
這個登入範例會限制使用者最多只能嘗試三次。每次輸入錯誤,剩餘次數會減少;當次數用完,登入按鈕將被停用。 登入畫面元件 畫面中需要使用者名稱、密碼、登入按鈕與剩餘次數文字。
Android ViewPager 多頁滑動與頁卡動畫實作
本文以類似行動社群應用的頁卡體驗為例,示範如何運用 ViewPager 完成多頁面的手勢切換,並讓頂部頁卡下方的白色橫條在切換時平滑移動。先認識 ViewPagerVie
Android 控件系列:CheckBox 建立方式、常用屬性與選中狀態監聽
CheckBox 是我們在表單類介面裡最常遇到的元件之一。本文從建立、屬性設定一路講到狀態變化的監聽寫法。 學習目標 1. 學會建立 CheckBox2. 掌握 Che
Android MediaPlayer:音訊播放與控制
MediaPlayer 簡介Android 提供多種方式播放音訊與影片,其中 MediaPlayer 是最常用來控制媒體播放的類別之一。它適合播放應用內建資源、網路串流或