編輯:初階開發
這篇文章不打算嚴格地逐點介紹 Android 的某個技術主題,比較接近我接觸 Android UI 開發至今的一些心得與個人理解。內容會牽涉到 Java、Android 開發、原始碼研究與設計模式等基礎知識,深入的部分還需要大家一起繼續挖掘。
第一個問題:Android 介面開發到底涵蓋哪些方面?
接觸 Android 一段時間之後,你心裡應該會形成這樣的印象——Android 開發可以切成兩塊:一塊是資源,一塊是對資源的操控。
前者是資源的導入、設定、整合,在一個典型的 Android 工程裡,它表現為 assets 資料夾中的音訊、視訊等原生資源檔,以及 res 資料夾裡各種 XML 文件與圖片檔。這些東西在程式執行時無法改變,是靜態的。後者則是資源的呼叫、使用、控制(甚至改變),表現為 src 與 gen 資料夾裡的 Java 檔(有些你手寫,有些由 ADT 透過 aidl 自動產生)。這部分在執行期是可變的,是動態的。
介面開發正好卡在這兩者之間最吃重的位置:它負責溝通「資源」與「對資源的操控」。也就是說,如果你想做出一個起碼「差強人意」的 Android 介面,你至少得先對這兩塊有大致的理解——要會寫 XML,才能堆出合乎邏輯的畫面結構;要有像樣的圖片資源(自己畫、自己 P,或知道該找人要什麼圖);要熟悉 android.widget 裡常用類別的用法與技巧,才能讓資料在執行時以舒服的形態呈現;甚至要對 Android 的視窗執行與管理機制有一定理解,才能更自由地定制介面特性。
第二個問題:Android 介面開發體現在哪些地方?
這就繞不開「用戶體驗」這個永恆話題了。體驗好,你就成功一半,而體驗的很大一部分正是介面。列幾個條件來看:
結論是:介面開發很重要,不能敷衍。
你可能會反駁:功能做得一塌糊塗、動不動就崩潰,介面漂亮又有什么用?身為工程師,這樣想很合理。但客戶不這麼想——他第一眼看到的只有介面,看不到你的資料庫怎麼運作。介面好不好看、順不順手,才是他真正感受到的東西。有了這個好印象打底,客戶才會想進一步了解你的應用。
我後來才發現這件事的份量:一開始我也覺得介面是整個流程中最短期、最輕鬆的部分,打算用最快速度弄完就去做功能。結果這正是專案爛尾的起點之一——介面決定了整個應用的功能模塊分布,它不只影響體驗,某些層面上甚至會反過來牽動功能模塊的設計與開發。而我的介面沒有想的那麼完美,於是功能寫完之後,大家只能對著自家應用流淚。
一句話總結:介面開發很重要,因為它直接關係用戶體驗,間接關係功能開發。
以下幾個是我曾經仔細分析過的成熟介面:
(1) 手機 QQ

登入畫面清爽美觀。
(2) Seesmic

好友列表簡約大方。
(3) bump

很有創意的一款軟體,風格與前一個類似——簡約而不簡單。也可以順帶觀察 TabActivity 的用法。
讀 GoF《設計模式》第一章時就會碰到這個最經典的應用程式設計模式:MVC(Model-View-Controller)。它最大的特點,在我理解來看,是實現了視圖與控制器的分離:視圖的更新經由模型,完全聽從控制器的安排。

看到這段描述,你想到什麼?我想到兩個類別:android.view.View 與 android.view.ViewGroup。前者很像書中的 View,後者很像 CompositeView——而且 ViewGroup 正是 View 的子類,它還可以再嵌套 View 與 ViewGroup。
這不是巧合。Android 介面系統的建構本身就是一個借鑑 MVC 的活例子。我們甚至找得到對應控制器的角色:android.view.ViewManager(雖然它只是一個介面)。再想想 android.widget 裡那些會顯示在螢幕上的類別,全都繼承自 View——是不是有一種豁然開朗的感覺?
你也許會問:講介面開發,怎麼跳到設計模式去了?因為 Android 也是人做出來的,而設計模式正是支撐它的依據之一。想了解 Android 的實質、想在開發時更游刃有餘,設計模式是一定要看的——至少它能讓你看懂系統各元件之間的依存關係。
再舉兩個例子:開發中常看到名字帶 Factory 的類別,那是工廠模式;把 Activity 的 launchMode 設為 singleInstance,那裡頭有單例模式的影子。更多就等你自己去發現了。
Activity 是什麼、TextView 是什麼,這裡不贅述。重點談談我自己常用到的幾類元件的特性與用法。
介面設計的第一步是整體框架結構,而這些框架在 Android 中由 ViewGroup 的各種子類實現:AbsoluteLayout、AdapterView、FrameLayout、LinearLayout、RelativeLayout、SlidingDrawer。
由於 Android 裝置市場群雄並起,各種顯示特性的機型都有。為了讓你的應用在各種機器上都能正確呈現,AbsoluteLayout 最好別用。真的要用,你必須有足夠巧妙的技術繞開它的缺陷,否則就得為每種螢幕尺寸各設計一套 UI。
SlidingDrawer 是個還算炫的元件,可以做出抽屜效果,藉此擴展那少得可憐的螢幕面積。Android 1.6 時代 Home 畫面下方那個點一下就拉出一堆應用的箭頭,就是 SlidingDrawer 的實例。
我自己用得最多的是 LinearLayout、RelativeLayout 與 AdapterView。
LinearLayout 和 RelativeLayout 主要用於整體佈局。介面裡經常出現「幾個 widget 成直排或橫排」的情況,這時通常就用 LinearLayout,它的 orientation 屬性決定內部元件的排列方向。RelativeLayout 不像 LinearLayout 那麼死板,兼容性又比 AbsoluteLayout 好得多,所以一旦涉及方位佈局,我會優先考慮它——android:layout_alignLeft、android:layout_alignParentLeft 這類屬性在方位佈局上實在好用。把這兩者結合起來,資訊量不大的畫面基本都能搞定,前面那個手機 QQ 登入畫面就是這樣做出來的。
AdapterView 則是資訊量大的場景的答案。它(泛型寫作 AdapterView<T extends Adapter>)本身是抽象類,是一整類「資料承載量極大、能顯示幾乎任何形式資料」的元件的父類。它的子類包含 Gallery、GridView、ListView、Spinner。這一系在顯示資料時都需要一個 Adapter 的實作類幫忙,例如 ArrayAdapter、BaseAdapter、CursorAdapter、SimpleAdapter、SimpleCursorAdapter、SpinnerAdapter。
結構弄好,接下來是往裡面放東西。常用的 View 有 TextView、ImageView、ProgressBar、AutoCompleteTextView、Button、CheckBox、EditText、ImageButton、ImageSwitcher、RadioButton、RadioGroup、SeekBar、Spinner、TabHost、TabWidget、TableLayout、WebView……深入這些元件是做出好介面的必經之路。
分享幾個實用經驗:
(1) 這些元件幾乎都有一個類似 SomeView(Context context) 的建構子。所以當你想在 Java 程式碼中動態產生 View 實例時,這就是萬用的入口。
(2) 想在程式碼中設定某個屬性、但不確定有沒有對應方法時,去查 Android 文件中該類的 XML Attributes 欄位。那裡列出了該元件在 XML 中所有可設定的屬性,而且會同時標註對應的 Java 方法——有的話你就能在程式碼裡動態設定,沒有的話就只能認了。舉例:View 類有個 android:background 屬性,文件裡標了對應的 setBackgroundResource(int),這就代表你能在執行期動態換背景。

(3) 這些元件並非一成不變,它們的可定制性極高。初階的做法是定義外觀(例如用 selector 設定 Button 在獲得焦點、失去焦點、按下等狀態下的不同樣式);進階的做法是定義行為——設定它對觸摸事件、按鍵事件如何反應。難怪有些應用會出現一些「禁止單擊、只准長按」的元件,那都是背後的事件機制在運作。
(4) 屬性大致可以分成兩組:套用於元件內部的,和套用於元件本身的。例如 android:layout_gravity 決定該元件在其父容器中的位置,而 android:gravity 決定其子元件在自己內部的位置;android:paddingLeft 指的是內部內容距左邊界的距離,android:marginLeft 指的則是該元件距父容器左邊界的距離。分清楚這兩組,佈局調起來會快很多。
最後一個建議:想理解某個 Android 類別,第一個該翻的一定是官方文件。雖然是英文,但只有它會告訴你最本源的消息。也可以採「廣而深」的方式,把某個主題下的類別地毯式掃過一遍,印象會深很多。推薦先讀 android.view.View 與 android.app.Activity 的文件,裡面有很多基礎而有力的知識。
說到這裡不得不抱怨一下:Android 的可視化介面開發工具 Layout Editor 實在不好用。所以推薦一個民間高手用 Java 寫的 DroidDraw,雖然仍有不足,但它的「所見即所得」做得比 Layout Editor 好得多。
你可以自己寫一個類別繼承 android.view.View,覆寫一些方法,加上自己的實作,就構成一個自製的 widget(當然也可以自訂 ViewGroup)。官方文件對這件事有完整的分類說明,值得一读:
實作自訂 View 時,通常從覆寫框架會呼叫的幾個標準方法開始,不必全部覆寫,實際上你可以只先覆寫 onDraw(Canvas)。文件把這些方法分成幾類:
Android 是完全開源的,你可以用 Git 拉下整個平台原始碼,甚至自己編出一個 Android 平台。但要注意:我們平常用的 SDK 只提供了原始碼中的一部分實作。這不是 Google 小氣,隱藏的部分是為了系統的安全與穩定(對照之下,某些平台的隱藏實作得靠社群破解才能用)。
既然原始碼在手,就得好好用。在原始碼環境下開發,可以實現 SDK 環境中做不到的介面效果,例如用自訂的虛擬按鈕來模擬實體 Menu 鍵。這是我當時正打算探索的方向。
結構很單純:外層 LinearLayout 鋪一張背景圖,內層再疊一層 logo 背景,最裡面用 RelativeLayout 把標語壓在底部並水平居中。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="@drawable/welcome_background"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/welcome_logo">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="390dip">
<TextView
android:text="@string/welcome_moto"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
public class Welcome extends Activity {
private final int SPLASH_DELAY_TIME = 5000;
private String Tag = "WelcomeActivity";
public void onCreate(Bundle savedInstanceState) {
Log.i(Tag, "onCreate()");
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.welcome);
new Handler().postDelayed(new Runnable() {
public void run() {
startActivity(new Intent(Welcome.this, Login.class));
Welcome.this.finish();
}
}, SPLASH_DELAY_TIME);
}
}
這裡有兩個細節值得注意。第一,順序:requestWindowFeature() 必須在 setContentView() 之前呼叫,否則會拋出例外。第二,為什麼用 Handler.postDelayed 而不是 Thread.sleep:sleep 會把主執行緒(也就是 UI 執行緒)整個 block 住,在 Android 上會直接觸發 ANR。postDelayed 是把 Runnable 丟進主執行緒的訊息佇列裡延後執行,完全不佔用執行緒。
登入畫面的佈局是層層嵌套的:最外層 LinearLayout 鋪背景,內部分三大塊——上方 250dip 的登入區、中間 110dip 的「其他登入方式」區、下方填滿剩餘空間的底部列。
登入區的做法值得一提:外層 RelativeLayout 給 250dip 高,內層 RelativeLayout 用 layout_alignParentBottom 貼底、寬 280dip,再放一個背景圖的方塊;方塊裡用垂直 LinearLayout 分出「logo 欄(80dip)」與「輸入欄(160dip)」兩側,輸入欄再用兩個水平 LinearLayout 分別放帳號列與密碼列,各用 layout_alignParentTop 與 layout_alignParentBottom 上下對齊。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="@drawable/login_background"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:layout_height="250dip"
android:layout_width="fill_parent">
<RelativeLayout
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_height="200dip"
android:layout_width="280dip"
android:background="@drawable/login_input_area_background">
<LinearLayout
android:orientation="vertical"
android:layout_height="160dip"
android:layout_width="240dip"
android:layout_centerInParent="true">
<LinearLayout
android:orientation="horizontal"
android:layout_height="100dip"
android:layout_width="fill_parent">
<LinearLayout
android:layout_width="80dip"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/login_input_area_logo_background">
<ImageView
android:layout_width="fill_parent"
android:layout_height="80dip"
android:src="@drawable/login_input_area_logo" />
<TextView
android:layout_width="fill_parent"
android:layout_height="20dip"
android:gravity="center_horizontal"
android:text="@string/login_textview_app_name_text"
android:textColor="@drawable/white" />
</LinearLayout>
<RelativeLayout
android:layout_width="160dip"
android:paddingLeft="10dip"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="48dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true">
<TextView
android:layout_width="42dip"
android:layout_height="50dip"
android:text="@string/login_textview_username_text"
android:textColor="@drawable/black" />
<EditText
android:id="@+id/login_edittext_username"
android:padding="5dip"
android:layout_width="108dip"
android:layout_height="fill_parent"
android:background="@drawable/login_edittext_background"
android:textColor="@drawable/black"
android:singleLine="true" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="48dip"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true">
<TextView
android:layout_width="42dip"
android:layout_height="50dip"
android:text="@string/login_textview_password_text"
android:textColor="@drawable/black" />
<EditText
android:id="@+id/login_edittext_password"
android:padding="5dip"
android:layout_width="108dip"
android:layout_height="fill_parent"
android:background="@drawable/login_edittext_background"
android:textColor="@drawable/black"
android:password="true"
android:singleLine="true" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
<!-- 其他登入方式區與底部列略,結構同上 -->
</LinearLayout>
這裡幾個屬性值得留意:密碼欄靠 android:password="true" 遮蔽輸入;android:padding 撐開 EditText 的內距讓文字不貼邊;登入鈕用 android:background="@drawable/login_button_log_in_selector" 換上狀態相關的背景圖。
這個 Activity 有幾段值得拿出來講的結構。
(1) 用工廠方法集中管理 Dialog。 三種對話框各有一個 create 方法,再由 dialogFactory 依類型分派,並快取成成員變數避免重複建立:
private final int ON_EXIT_DIALOG = 1;
private final int ABOUT_US_DIALOG = 2;
private final int LOG_IN_MODE_SELECT_DIALOG = 3;
private Dialog dialogFactory(int dialogType) {
switch (dialogType) {
case ON_EXIT_DIALOG: return createOnExitDialog();
case ABOUT_US_DIALOG: return createAboutUsDialog();
case LOG_IN_MODE_SELECT_DIALOG: return createLoginModeDialog();
}
return null;
}
(2) 攔截返回鍵做二次確認。 直接 finish 太容易被誤觸,實務上幾乎都會加一層確認:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
dialogFactory(ON_EXIT_DIALOG).show();
}
return false;
}
自訂 Dialog 的樣式時,用 getLayoutInflater().inflate() 把自己的 XML 塞進 AlertDialog.Builder,再對 inflate 出來的 View 做 findViewById 綁事件——注意是對 dialogView 找元件,不是對 Activity 找,這是常犯的錯:
private Dialog createOnExitDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View dialogView = this.getLayoutInflater()
.inflate(R.layout.login_alertdialog_on_exit, null);
dialogBuilder.setView(dialogView);
onExitDialog = dialogBuilder.create();
dialogView.findViewById(R.id.login_button_alertdialog_on_exit_yes)
.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) { Login.this.finish(); }
});
dialogView.findViewById(R.id.login_button_alertdialog_on_exit_no)
.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) { onExitDialog.dismiss(); }
});
return onExitDialog;
}
(3) 選單式的登入模式選擇用 setItems 搭配字串陣列資源,比自己做一個 Dialog 省事:
private Dialog createLoginModeDialog() {
return new AlertDialog.Builder(this)
.setTitle(R.string.login_dialog_login_mode_select_title_text)
.setItems(R.array.login_mode_selector_array,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: textViewLoginMode.setText("完整模式"); break;
case 1: textViewLoginMode.setText("Gps模式"); break;
case 2: break;
}
}
}).create();
}
(4) 元件初始化集中在一處。 把 findViewById 與事件綁定收攏到 initializeView(),onCreate 只負責呼叫它,可讀性會好很多:
private void initializeView() {
buttonLogin = (Button) findViewById(R.id.login_button_log_in);
buttonLogin.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Login.this, DuringLogin.class));
}
});
buttonLoginMode = (Button) findViewById(R.id.login_button_log_in_mode);
buttonLoginMode.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
dialogFactory(LOG_IN_MODE_SELECT_DIALOG).show();
}
});
textViewLoginMode = (TextView)
findViewById(R.id.login_textview_current_log_in_mode);
}
另外,選單部分用 onCreateOptionsMenu 搭配 MenuInflater 從 R.menu.login_menu 載入,再在 onOptionsItemSelected 中分派——這比硬寫 add() 好維護。
歡迎畫面:

登入畫面:

回頭看這整篇,如果只能留一個結論,那就是:介面不是功能的裝飾,而是功能的骨架。你先畫出什麼樣的畫面、怎麼分頁、怎麼跳轉,功能模塊的邊界就跟著定下來了。所以千萬別把介面當成最後才做的事。
以上程式碼是當年的寫法,用來說明思路還可以,但直接搬到今日的專案上有幾點必須調整:dip 已更名為 dp;fill_parent 改為 match_parent;android:password 應改用 android:inputType="textPassword";Activity 的委建寫法與 Dialog 管理也已有 Jetpack(ViewModel、DialogFragment、Navigation)等更完善的方案。原則不變,工具持續演進。
Android 調試工具 Monkey 壓力測試實戰
許多 Android 開發者因為沒有充分測試自己的軟體,導致應用頻頻出現 FC(Force Close)。其實,我們可以借助 Android 固件自帶的 Monkey 工
Thread、Looper、Handler 與 Message 詳解
在 Android 中,UI 更新通常必須在主執行緒進行,因此耗時任務需放在背景執行緒,再透過 Handler 或 AsyncTask 將結果回傳 UI 執行緒。Thre
Android ApiDemo 逐項拆解:Graphics 與 View 篇(下)
接續上一篇,這裡整理 ApiDemo 中 Gallery、Grid、ImageSwitcher、ImageView、LayoutAnimation 與 LinearLay
Android 調試技巧:Eclipse 行號顯示與 Logcat 錯誤定位
很多剛入門 Android 的開發者,常會遭遇 Force Close 或 ANR 這類問題。通常我們可以透過 Android 系統的錯誤日誌工具 Logcat 查看出錯