編輯:關於 Android 程式設計
本文接續上篇,整理 Android 官方文件中 Resource Types 剩下的三大主角:Drawable、Layout 與 Menu 資源。想對照原文的讀者,可以參考官方章節《Drawable Resources》《Layout Resource》《Menu Resource》。
版面配置資源用來定義畫面元件的 UI 結構,也就是我們最熟悉的 XML 佈局檔。
檔案位置:
res/layout/filename.xml
引用方式:
In Java: R.layout.filename
In XML: @[package:]layout/filename
根標籤可以是 ViewGroup、View,或 <merge> 三者之一。
標籤與屬性說明:
<viewgroup>:承載其他 View 的容器,例如 LinearLayout、RelativeLayout、FrameLayout。值得注意的是,並非所有 ViewGroup 都能在佈局中直接放入子 View——例如 AdapterView,它的子項來自 Adapter 而非 XML。
android:id:資源 ID。android:layout_height:dp 數值或關鍵字(wrap_content、match_parent),不可省略。android:layout_width:同上,不可省略。<requestFocus>:任何 View 都可以包含這個標籤,表示程式首次載入時由該 View 取得焦點。同一個佈局檔中只能使用一次。
<include>:引用另一個佈局檔,達到複用的目的。
layout:不可省略,指定要引用的佈局資源。android:id:可覆寫被引用佈局根 View 的 ID。android:layout_height / android:layout_width:可覆寫被引用佈局根 View 的寬高。<merge>:作為根標籤使用,但它本身並不會在佈局樹中佔據節點。其中的元素會被直接合併到引用它的父容器中,常用來消除多餘的巢狀層級。
示例:
<!-- res/layout/main_activity.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
在 Activity 中引用:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
選單資源為程式提供各類選單項,包含 Options Menu、Context Menu 與 submenu。在 Java 端透過 MenuInflater 類別的方法載入。
檔案位置: res/menu/filename.xml
引用方式:
In Java: R.menu.filename
In XML: @[package:]menu.filename
根標籤 <menu>:不可省略,必須作為選單資源的根節點,內部應包含 <item> 和/或 <group>。其中 xmlns:android 也是必填,固定為 "https://schemas.android.com/apk/res/android"。
<item>:單一選單項。若內部再包一層 <menu>,那層就是子選單。常用屬性:
android:id:資源 ID。android:title:選單項顯示文字。android:titleCondensed:精簡版文字,當 android:title 空間不足時改顯示這個。android:icon:drawable 資源,選單項圖示。android:onClick:點擊時呼叫的方法名。該方法必須定義在 Activity 中、必須是 public,且唯一參數為 MenuItem。android:actionLayout:自訂標題欄的版面配置資源。android:actionViewClass:要在標題欄呈現的 View 全限定類名,例如 "android.widget.SearchView"。android:actionProviderClass:菜單項的 Provider 全限定類名,例如 "android.widget.ShareActionProvider"。android:alphabeticShortcut / android:numericShortcut:為該項指定字母/數字快捷鍵。android:checkable、android:checked、android:visible、android:enabled:Boolean 型別,分別控制是否可勾選、預設是否勾選、是否可見、是否啟用。android:orderInCategory:Integer 型別,決定排序權重。android:showAsAction 的可用值:
| Value | 說明 |
|---|---|
| ifRoom | 僅當標題欄有空間時顯示,否則收進 overflow 選單。 |
| withText | 標題欄有空間時,連同 title 文字一起顯示。 |
| never | 永不在標題欄顯示,一律收進 overflow。 |
| collapseActionView | 將操作視窗折疊成一個按鈕,使用者點擊後才展開;未折疊時會持續佔用標題欄空間。 |
android:menuCategory 對應 Menu 類別中的 CATEGORY_* 欄位,可用值為 container(屬於某個容器的一部分)、system(系統提供)、secondary(使用者提供的次要選項)、alternative(替代選項)。
<group>:定義一組選單項。除了 android:id、android:visible、android:enabled、android:menuCategory、android:orderInCategory 之外,最關鍵的是 android:checkableBehavior:
| Value | 說明 |
|---|---|
| none | 群組內不含可勾選的項目。 |
| all | 所有項目都可勾選,呈現為 checkbox。 |
| single | 只能單選,呈現為 radiobutton。 |
示例:
<!-- res/menu/example_menu.xml -->
<menu xmlns:android="https://schemas.android.com/apk/res/android">
<item
android:id="@+id/item1"
android:icon="@drawable/group_item1_icon"
android:showAsAction="ifRoom|withText"
android:title="@string/item1">
<group android:id="@+id/group">
<item
android:id="@+id/group_item1"
android:onClick="onGroupItemClick"
android:title="@string/group_item1" />
<item
android:id="@+id/group_item2"
android:onClick="onGroupItemClick"
android:title="@string/group_item2" />
</group>
<menu>
<item
android:id="@+id/submenu_item1"
android:title="@string/submenu_item1" />
</menu>
</item>
</menu>
在 Java 中載入並處理:
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.example_menu, menu);
return true;
}
public void onGroupItemClick(MenuItem item) {
// 透過 onClick 屬性觸發的群組項目點擊會走到這裡
// item 參數指出被點擊的是哪一項
// 其餘選單項的點擊由 onOptionsItemSelected() 處理
}
Drawable 泛指一切「可以在螢幕上畫出來的東西」。依呈現形式不同,可分為以下幾類:
Bitmap File:位圖檔(.png / .jpg / .gif),對應 BitmapDrawable。Nine-Patch File:可指定方向拉伸而不失真的 .9.png,對應 NinePatchDrawable。Layer List:以層次順序疊放一組 Drawable,索引最大者在最上層,對應 LayerDrawable。State List:依控件狀態切換不同 Drawable,對應 StateListDrawable。Level List:管理多個 Drawable 並以 level 值切換,對應 LevelListDrawable。Transition Drawable:在兩個 Drawable 之間做淡入淡出切換,對應 TransitionDrawable。Inset Drawable:把一個 Drawable 內縮指定距離後嵌入,常用於背景需留白的情況。Clip Drawable:依當前尺寸裁剪另一個 Drawable,對應 ClipDrawable。Scale Drawable:依當前尺寸縮放另一個 Drawable,對應 ScaleDrawable。Shape Drawable:以 XML 定義形狀、顏色與漸層,對應 ShapeDrawable。Android 支援三種位圖格式,官方建議優先使用 .png(推薦)、.jpg(可接受)、.gif(不推薦)。
檔案位置: res/drawable/filename.png(或 .jpg / .gif)
引用方式: Java 端 R.drawable.filename;XML 端 @[package:]drawable/filename
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/myimage" />
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.myimage);
以 <bitmap> 標籤在 XML 中對位圖做額外設定。
檔案位置: res/drawable/filename.xml
屬性:
android:src:來源 drawable 資源,不可省略。android:antialias:是否開啟抗鋸齒。android:dither:當圖片像素格式與螢幕不符時(例如圖為 ARGB 8888 而螢幕為 RGB 565)是否做像素適配。android:filter:是否開啟圖片濾鏡。android:gravity:圖片在容器中的顯示位置。android:mipMap:是否開啟 mipmap 提示。android:tileMode:拼貼模式。disabled(預設,不拼貼)、clamp(重複邊緣像素)、repeat(雙向重複)、mirror(鏡像重複)。<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
android:src="@drawable/icon"
android:tileMode="repeat" />
Nine-Patch 是可拉伸圖片的標準解法,副檔名為 .9.png。它在普通圖片四周多出 1dp 的邊界:左側與上側的 1dp 標示可拉伸區域,右側與下側的 1dp 標示內容(文字)的對齊位置。用九宮格切分的概念來理解最好記——四角不拉伸、兩側單向拉伸、中央雙向拉伸。
檔案位置: res/drawable/filename.9.png
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/myninepatch" />
以 <layer-list> 包多個 <item>,每個 item 代表一個層級。
檔案位置: res/drawable/filename.xml
屬性:android:drawable(不可省略)、android:id,以及 android:top / android:right / android:bottom / android:left 四個偏移量。
<!-- res/drawable/layers.xml -->
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="https://schemas.android.com/apk/res/android">
<item>
<bitmap android:gravity="center" android:src="@drawable/android_red" />
</item>
<item android:left="10dp" android:top="10dp">
<bitmap android:gravity="center" android:src="@drawable/android_green" />
</item>
<item android:left="20dp" android:top="20dp">
<bitmap android:gravity="center" android:src="@drawable/android_blue" />
</item>
</layer-list>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/layers" />
效果如下:

為同一個控件在不同狀態下換上不同 Drawable。以 Button 為例,它有按下、未按下、取得焦點等多種狀態。
檔案位置: res/drawable/filename.xml
根標籤 <selector> 不可省略,內部包含多個 <item>。
selector 屬性:
android:constantSize:為 true 時狀態切換不會改變 Drawable 尺寸,預設 false。android:dither:預設 true,像素格式與螢幕不符時自動適配。android:variablePadding:為 true 時狀態切換會連帶改變控件的 padding,預設 false。item 狀態屬性(皆為 Boolean):state_pressed(正在被點擊)、state_focused(取得焦點)、state_hovered(游標懸停,行為通常與 focused 相同)、state_selected(選中)、state_checkable(可勾選)、state_checked(已勾選)、state_enabled(可接受點擊)、state_activated(已點擊標記,點擊後會持續變色)、state_window_focused(所屬視窗在前台)。
示例:
<!-- res/drawable/button.xml -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/button_focused" android:state_focused="true" />
<item android:drawable="@drawable/button_focused" android:state_hovered="true" />
<item android:drawable="@drawable/button_normal" />
</selector>
這裡有個關鍵觀念:selector 是「由上往下第一個命中就採用」,所以 state_pressed 必須寫在最前面,作為預設值的那個 item(不帶任何 state 屬性)則必須擺在最後。
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button" />
管理多個 Drawable,透過程式的 setLevel() 決定顯示哪一張。
檔案位置: res/drawable/filename.xml
item 屬性:android:drawable(不可省略)、android:maxLevel(該項的最大 level)、android:minLevel(最小 level)。
<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/status_off" android:maxLevel="0" />
<item android:drawable="@drawable/status_on" android:maxLevel="1" />
</level-list>
典型應用是省電模式的電量圖示、信號強弱格數等——圖片資源一次打包,執行期只切 level,不必重新載入。
在兩個 Drawable 之間做淡入淡出的交叉轉場。
檔案位置: res/drawable/filename.xml
<!-- res/drawable/transition.xml -->
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/on" />
<item android:drawable="@drawable/off" />
</transition>
<ImageButton
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/transition" />
Java 端觸發,500 毫秒內從第一張切換到第二張:
ImageButton button = (ImageButton) findViewById(R.id.button);
TransitionDrawable drawable = (TransitionDrawable) button.getDrawable();
drawable.startTransition(500);
若要反向切回,呼叫 reverseTransition(500) 即可。
把一個 Drawable 往內縮指定距離後再嵌入,常用於讓背景比 View 本身小一圈的視覺效果。
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="https://schemas.android.com/apk/res/android"
android:drawable="@drawable/background"
android:insetLeft="10dp"
android:insetTop="10dp" />
屬性:android:drawable(不可省略)、android:insetLeft、android:insetTop、android:insetRight、android:insetBottom,皆為 Dimension 型別。
用純 XML 畫出矩形、橢圓、線條或圓環,不必準備圖片素材。這是在 Android 上取代「切圖」最實用的技巧。
檔案位置: res/drawable/filename.xml
<shape> 為根標籤,android:shape 可選 rectangle(預設)、oval、line、ring。內部可組合以下子標籤:
<corners>:圓角。僅在 shape 為 rectangle 時有效。android:radius 統一設定,或用 topLeftRadius / topRightRadius / bottomLeftRadius / bottomRightRadius 分別設定。<gradient>:漸層。android:angle(0 為左至右,90 為下至上,預設 0)、startColor、centerColor、endColor、centerX / centerY(0.0–1.0)、type(linear 線性預設值、radial 放射、sweep 掃描)。<padding>:與父容器的內距,含 left / right / top / bottom。<size>:形狀尺寸,含 android:width 與 android:height。<solid>:純色填充,android:color 指定顏色。<stroke>:邊框。android:width 線寬、android:color 線色、android:dashWidth 虛線長度、android:dashGap 虛線間距。示例(45 度漸層圓角方塊):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="45"
android:startColor="#FFFF0000"
android:endColor="#80FF00FF" />
<padding
android:left="7dp"
android:right="7dp"
android:top="7dp"
android:bottom="7dp" />
<corners android:radius="8dp" />
</shape>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/gradient_box" />
也可以在 Java 端動態套用:
Resources res = getResources();
Drawable shape = res.getDrawable(R.drawable.gradient_box);
TextView tv = (TextView) findViewById(R.id.textview);
tv.setBackground(shape);
這三類資源幾乎撐起了 Android UI 開發的日常:Layout 決定結構、Menu 決定操作入口、Drawable 決定視覺呈現。特別是 Drawable,熟練使用 Shape Drawable 與 Selector 之後,很多原本需要設計師切圖的簡單元件都能改由 XML 描述,不僅減小 APK 體積,也讓不同解析度螢幕的適配變得輕鬆。
Android 百度語音整合實務:語音喚醒、識別與合成的完整交互
百度語音提供語音喚醒、語音識別與語音合成能力,適合用來打造免手動的語音交互流程。使用者說出喚醒詞後,應用可進入識別狀態,並透過合成語音回饋結果。 整合重點 使用百度語音
Android 開發通用工具類整理
工具類的價值 開發過程中常會遇到重複性程式碼,例如網路請求、資料儲存、字串處理與日期格式化。將這些邏輯整理成工具類,可以減少重複撰寫,也能提升專案維護效率。 使用建議
兩步打造華麗引導頁:RxJava 加持的首次啟動引導流程
前言在上一篇《基於 RxJava 實現酷炫啟動頁》中,我們用 RxJava 做了一個帶縮放動畫的啟動頁。這次要在此基礎上加一個能力:首次使用 App 時展示功能引導頁。實
Android 熱修補丁方案設計與持續交付實踐
Android 的碎片化不僅體現在系統版本與機型上,也體現在發行渠道上——每個市場都有自己的政策與審核節奏。一次版本發布,對開發同學來說往往是漫長的煎熬。iOS 兩三天就