編輯:初階開發
ApiDemo 是 Android SDK 附帶的範例集,幾乎涵蓋了所有常用 API。這一篇把 Graphics 與 View 兩個 package 裡的關鍵範例整理成可查閱的筆記,並補上每個屬性實際在做什麼。

這個範例示範三件事:用 Path 畫出曲線、把文字沿路徑排列、以及逐字定位繪製。
先用 cubicTo 建立一條三次貝茲曲線:
private static void makePath(Path p) {
p.moveTo(10, 0);
p.cubicTo(100, -50, 200, 50, 300, 0); // 貝茲曲線
}
接著是逐字定位的關鍵。Paint.getTextWidths() 會把每個字元的寬度填進陣列,我們再把這些寬度「累加」起來,交出一組交錯排列的 [x, y] 座標:
private float[] buildTextPositions(String text, float y, Paint paint) {
float[] widths = new float[text.length()];
// 先取得每個字元的寬度
int n = paint.getTextWidths(text, widths);
// 填入座標,x 值為累計寬度,並在兩者之間插入 y 值
float[] pos = new float[n * 2];
float accumulatedX = 0;
for (int i = 0; i < n; i++) {
pos[i * 2 + 0] = accumulatedX;
pos[i * 2 + 1] = y;
accumulatedX += widths[i];
}
return pos;
}
在 onDraw() 中,先用紅線畫出基線,再用 Paint.Align.LEFT 從基準點開始繪製:

p.setColor(0x80FF0000);
canvas.drawLine(x, y, x, y + DY * 3, p); // (x, y) 為基準線
p.setColor(Color.BLACK);
canvas.translate(0, DY);
p.setTextAlign(Paint.Align.LEFT);
canvas.drawText(TEXT_L, x, y, p); // 以 (x, y) 為基準點,左對齊
再用綠線標出每個字元的位置,並以 drawPosText 逐字繪製:

p.setColor(0xBB00FF00);
for (int i = 0; i < pos.length / 2; i++) {
canvas.drawLine(pos[i * 2 + 0], pos[i * 2 + 1] - DY,
pos[i * 2 + 0], pos[i * 2 + 1] + DY * 2, p);
}
p.setColor(Color.BLACK);
p.setTextAlign(Paint.Align.LEFT);
canvas.drawPosText(POSTEXT, pos, p);
最後是沿著路徑繪字,三種對齊方式各示範一次:

canvas.drawPath(mPath, mPathPaint);
p.setTextAlign(Paint.Align.LEFT);
canvas.drawTextOnPath(TEXTONPATH, mPath, 0, 0, p);
canvas.translate(0, DY * 1.5f);
canvas.drawPath(mPath, mPathPaint);
p.setTextAlign(Paint.Align.CENTER);
canvas.drawTextOnPath(TEXTONPATH, mPath, 0, 0, p);
canvas.translate(0, DY * 1.5f);
canvas.drawPath(mPath, mPathPaint);
p.setTextAlign(Paint.Align.RIGHT);
canvas.drawTextOnPath(TEXTONPATH, mPath, 0, 0, p);

把字型檔放進 assets/fonts/,用 Typeface.createFromAsset() 讀出來即可:
mFace = Typeface.createFromAsset(getContext().getAssets(),
"fonts/samplefont.ttf");
在 onDraw() 中,把 typeface 設為 null 就是系統預設字型,設成我們的物件則是自訂字型:
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
mPaint.setTypeface(null);
canvas.drawText("Default", 10, 100, mPaint);
mPaint.setTypeface(mFace);
canvas.drawText("Custom", 10, 200, mPaint);
}

展示 Unicode 字元對照表,概念單純,程式碼很長,這裡不展開。

操作 Canvas.drawVertices(),觸碰螢幕時圖片會隨手指變形,效果類似橡皮筋。這個 API 適合做簡單的 mesh 扭曲,但正式專案裡更常用 OpenGL 處理。

這個範例把 Porter-Duff 的 16 種模式全部排出來給你看。先準備三張素材:圓形(dst)、方形(src)、以及馬賽克棋盤背景。
// 圓形畫法(dst)
static Bitmap makeDst(int w, int h) {
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(0xFFFFCC44);
c.drawOval(new RectF(0, 0, w * 3 / 4, h * 3 / 4), p);
return bm;
}
// 正方形畫法(src)
static Bitmap makeSrc(int w, int h) {
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setColor(0xFF66AAFF);
c.drawRect(w / 3, h / 3, w * 19 / 20, h * 19 / 20, p);
return bm;
}
背景棋盤用 2×2 的點陣圖當 shader,並放大 6 倍讓格子明顯可見:
Bitmap bm = Bitmap.createBitmap(new int[] {
0xFFFFFFFF, 0xFFCCCCCC,
0xFFCCCCCC, 0xFFFFFFFF }, 2, 2, Bitmap.Config.RGB_565);
mBG = new BitmapShader(bm, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
Matrix m = new Matrix();
m.setScale(6, 6); // 放大 6 倍
mBG.setLocalMatrix(m);
16 種模式列成陣列:
private static final Xfermode[] sModes = {
new PorterDuffXfermode(PorterDuff.Mode.CLEAR),
new PorterDuffXfermode(PorterDuff.Mode.SRC),
new PorterDuffXfermode(PorterDuff.Mode.DST),
new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER),
new PorterDuffXfermode(PorterDuff.Mode.DST_OVER),
new PorterDuffXfermode(PorterDuff.Mode.SRC_IN),
new PorterDuffXfermode(PorterDuff.Mode.DST_IN),
new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT),
new PorterDuffXfermode(PorterDuff.Mode.DST_OUT),
new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP),
new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP),
new PorterDuffXfermode(PorterDuff.Mode.XOR),
new PorterDuffXfermode(PorterDuff.Mode.DARKEN),
new PorterDuffXfermode(PorterDuff.Mode.LIGHTEN),
new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY),
new PorterDuffXfermode(PorterDuff.Mode.SCREEN)
};
核心邏輯在 onDraw():先畫棋盤底,再把 dst 畫進一個暫存圖層,切換 xfermode 後畫上 src,最後復原圖層。
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
Paint labelP = new Paint(Paint.ANTI_ALIAS_FLAG);
labelP.setTextAlign(Paint.Align.CENTER);
Paint paint = new Paint();
paint.setFilterBitmap(false);
canvas.translate(15, 35);
int x = 0;
int y = 0;
for (int i = 0; i < sModes.length; i++) {
// 畫邊框
paint.setStyle(Paint.Style.STROKE);
paint.setShader(null); // 傳 null 清掉先前的 shader
canvas.drawRect(x - 0.5f, y - 0.5f, x + W + 0.5f, y + H + 0.5f, paint);
// 畫棋盤底
paint.setStyle(Paint.Style.FILL);
paint.setShader(mBG);
canvas.drawRect(x, y, x + W, y + H, paint);
// 把 src / dst 範例畫進暫存圖層
int sc = canvas.saveLayer(x, y, x + W, y + H, null,
Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG
| Canvas.HAS_ALPHA_LAYER_SAVE_FLAG
| Canvas.FULL_COLOR_LAYER_SAVE_FLAG
| Canvas.CLIP_TO_LAYER_SAVE_FLAG);
canvas.translate(x, y);
canvas.drawBitmap(mDstB, 0, 0, paint);
paint.setXfermode(sModes[i]);
canvas.drawBitmap(mSrcB, 0, 0, paint);
paint.setXfermode(null); // 傳 null 清掉先前的 xfermode
canvas.restoreToCount(sc);
// 畫標籤
canvas.drawText(sLabels[i], x + W / 2, y - labelP.getTextSize() / 2, labelP);
x += W + 10;
if ((i % ROW_MAX) == ROW_MAX - 1) { // 一行畫滿就換行
x = 0;
y += H + 30;
}
}
}
這裡有個容易踩到的地雷:一定要用成對的 saveLayer() / restoreToCount()。若把它們換成普通的 canvas.save() / canvas.restore(),畫出來的結果會完全跑掉,變成下圖這樣:

int sc = canvas.saveLayer(x, y, x + W, y + H, null,
Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG
| Canvas.HAS_ALPHA_LAYER_SAVE_FLAG
| Canvas.FULL_COLOR_LAYER_SAVE_FLAG
| Canvas.CLIP_TO_LAYER_SAVE_FLAG);
// canvas.save(); ← 不能這樣寫
canvas.restoreToCount(sc);
// canvas.restore(); ← 也不能這樣寫
差別在於:saveLayer 會配置一塊獨立的離屏緩衝區,合成模式必須在這塊緩衝區上運算才會正確;save 只存還原堆疊,沒有獨立圖層可用。

點下 Login 按鈕後,密碼輸入框會左右抖動,這是表單驗證失敗時常見的提示手法。
public class Animation1 extends Activity implements View.OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animation_1);
View loginButton = findViewById(R.id.login);
loginButton.setOnClickListener(this);
}
public void onClick(View v) {
// 從資源載入 Animation 物件
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
// 對指定 View 啟動動畫
findViewById(R.id.pw).startAnimation(shake);
}
}
動畫定義放在 res/anim/shake.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="https://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="10"
android:duration="1000"
android:interpolator="@anim/cycle_7" />
這是 translate 類型動畫,X 從 0 移到 10,為期一秒。關鍵是 android:interpolator="@anim/cycle_7" 這行——它掛上了一個「循環插入器」。
res/anim/cycle_7.xml:
<?xml version="1.0" encoding="utf-8"?>
<cycleInterpolator xmlns:android="https://schemas.android.com/apk/res/android"
android:cycles="7" />
也就是說,這段位移在 1 秒內會來回震盪 7 次,看起來就是抖動。

上方是一個 ViewFlipper,依序翻轉四個 TextView;下方是一個 Spinner,用來切換翻轉動畫的風格。
版面配置:一個 ViewFlipper 裡含四個 TextView,android:flipInterval="2000" 代表每 2 秒自動換一次。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ViewFlipper android:id="@+id/flipper"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:flipInterval="2000"
android:layout_marginBottom="20dip" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="26sp"
android:text="@string/animation_2_text_1"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="26sp"
android:text="@string/animation_2_text_2"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="26sp"
android:text="@string/animation_2_text_3"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="26sp"
android:text="@string/animation_2_text_4"/>
</ViewFlipper>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:text="@string/animation_2_instructions" />
<Spinner android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Spinner 選擇時,透過 setInAnimation / setOutAnimation(兩者都是 ViewAnimator 的方法)決定進場與退場動畫:
public void onItemSelected(AdapterView parent, View v, int position, long id) {
switch (position) {
case 0:
mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
R.anim.push_up_in));
mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
R.anim.push_up_out));
break;
case 1:
mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
R.anim.push_left_in));
mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
R.anim.push_left_out));
break;
case 2:
mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
break;
default:
mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
R.anim.hyperspace_in));
mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
R.anim.hyperspace_out));
break;
}
}
幾個動畫資源檔:push_up_in.xml 是位移加淡入,push_up_out.xml 反之;push_left_in.xml 走水平方向;hyperspace_in.xml 用 android:startOffset="1200" 延遲啟動。
<!-- res/anim/push_up_in.xml -->
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
<translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="300"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>
<!-- res/anim/push_up_out.xml -->
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
<translate android:fromYDelta="0" android:toYDelta="-100%p" android:duration="300"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="300" />
</set>
<!-- res/anim/push_left_in.xml -->
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
<translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="300"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>
<!-- res/anim/hyperspace_in.xml -->
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="https://schemas.android.com/apk/res/android"
android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300"
android:startOffset="1200" />
hyperspace_out.xml 則示範了巢狀 <set> 的寫法——外層用 android:shareInterpolator="false" 讓子動畫各自使用自己的插入器,內層再用 android:startOffset="700" 做時間錯開:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<scale android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:fromXScale="1.0" android:toXScale="1.4" android:fromYScale="1.0"
android:toYScale="0.6" android:pivotX="50%" android:pivotY="50%"
android:fillAfter="false" android:duration="700" />
<set android:interpolator="@android:anim/accelerate_interpolator"
android:startOffset="700">
<scale android:fromXScale="1.4" android:toXScale="0.0"
android:fromYScale="0.6" android:toYScale="0.0" android:pivotX="50%"
android:pivotY="50%" android:duration="400" />
<rotate android:fromDegrees="0" android:toDegrees="-45"
android:pivotX="50%" android:pivotY="50%"
android:duration="400" />
</set>
</set>
這幾個動畫檔案都可以直接套用到 ImageView 上。
Animation.setInterpolator(Interpolator i) 決定動畫的加速度曲線,不設定的話預設是線性(等速)。

先建立一個位移動畫並掛到目標 View 上:

final View target = findViewById(R.id.target); // TextView
final View targetParent = (View) target.getParent(); // TextView 的父 View
Animation a = new TranslateAnimation(0.0f,
targetParent.getWidth()
- target.getWidth() - targetParent.getPaddingLeft()
- targetParent.getPaddingRight(), 0.0f, 0.0f);
a.setDuration(1000); // 持續 1 秒
a.setStartOffset(300);
a.setRepeatMode(Animation.RESTART); // 重複模式
a.setRepeatCount(Animation.INFINITE); // 無限次
Android 內建的七種 Interpolator:
switch (position) {
case 0:
a.setInterpolator(AnimationUtils.loadInterpolator(this,
android.R.anim.accelerate_interpolator));
break;
case 1:
a.setInterpolator(AnimationUtils.loadInterpolator(this,
android.R.anim.decelerate_interpolator));
break;
case 2:
a.setInterpolator(AnimationUtils.loadInterpolator(this,
android.R.anim.accelerate_decelerate_interpolator));
break;
case 3:
a.setInterpolator(AnimationUtils.loadInterpolator(this,
android.R.anim.anticipate_interpolator));
break;
case 4:
a.setInterpolator(AnimationUtils.loadInterpolator(this,
android.R.anim.overshoot_interpolator));
break;
case 5:
a.setInterpolator(AnimationUtils.loadInterpolator(this,
android.R.anim.anticipate_overshoot_interpolator));
break;
case 6:
a.setInterpolator(AnimationUtils.loadInterpolator(this,
android.R.anim.bounce_interpolator));
break;
}
target.startAnimation(a);
實際選用的差別很明顯:accelerate 是越跑越快,decelerate 是起步衝很快再減速,anticipate 會先往反方向拉一下再衝出去,overshoot 則是衝過頭再回彈,anticipate_overshoot 兩者兼具,bounce 則像球落地後的彈跳。
package 為 com.example.android.apis.animation,示範圖片之間的 3D 翻轉效果。

版面是一個 FrameLayout,裡面放一個 ListView 與一個 ImageView,動畫就是這兩個 View 互相切換的過場。


版面很簡單,一個 TextView 加上一個 AutoCompleteTextView:
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/autocomplete_1_country" />
<AutoCompleteTextView android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
程式碼端只要給它一個 Adapter,並把國家清單當資料來源:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
textView.setAdapter(adapter);
COUNTRIES 是一個靜態字串陣列,內容就是各國國名(Afghanistan、Albania、Algeria… 一路到 Zimbabwe)。這裡要點是:Adapter 決定下拉選單的樣式(simple_dropdown_item_1line 是單行清單項),而陣列決定候選資料。

功能與 AutoComplete1 完全相同,只是版面不同。關鍵在於 android:gravity="bottom",它讓內容整體貼齊父容器底部:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="bottom">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/autocomplete_2_focus" />
<LinearLayout ... >
...
</LinearLayout>

改用 MultiAutoCompleteTextView,可以在同一個欄位裡以逗號分隔輸入多個項目,每個項目各自觸發提示。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/autocomplete_7_country" />
<MultiAutoCompleteTextView android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.edit);
textView.setAdapter(adapter);
textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
差別就在最後那行 setTokenizer——它告訴控制項「分隔符號是什麼」,也就是提示要在哪個位置重新開始比對。
Baseline(基線)指的是文字底部的那條參考線。這幾個範例示範不同容器下如何讓元件對齊。
Baseline1:直接排列 TextView 與 Button,用 android:layout_marginRight="30dip" 在文字右側留出 30 像素空白。

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="30dip"
android:text="@string/baseline_1_label" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="30dip"
android:text="@string/baseline_1_button" />
Baseline3:改用水平 LinearLayout,並用 android:layout_gravity="center_vertical" 讓子元件在父容器垂直居中。

<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:layout_height="0dip">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dip"
android:layout_gravity="center_vertical"
android:text="@string/baseline_3_label" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dip"
android:layout_gravity="center_vertical"
android:text="@string/baseline_3_button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="20sp"
android:text="@string/baseline_3_bigger" />
</LinearLayout>
Baseline4:父容器改成水平 LinearLayout,子 View 同時套用 android:layout_gravity="center_vertical" 與 android:gravity="bottom",觀察兩者的作用位置差異。

Baseline6:用 RelativeLayout 搭配 android:layout_alignBaseline,把 TextView 對齊到 EditText 的基線上。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:id="@+id/anchor"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="20sp"
android:text="@string/baseline_6_multi_line" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/anchor"
android:layout_alignRight="@id/anchor"
android:text="@string/baseline_6_baseline" />
</RelativeLayout>
Baseline7:把 anchor 用 android:layout_alignParentTop 與 android:layout_alignParentLeft 釘在父容器的左上角,另一個 TextView 則用 android:layout_alignParentRight 靠右,並以 android:layout_alignBaseline="@id/anchor" 對齊基線。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/anchor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textStyle="bold"
android:text="@string/baseline_7_fat" />
<TextView
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignBaseline="@id/anchor"
android:layout_height="wrap_content"
android:text="@string/baseline_7_lean" />
</RelativeLayout>

示範普通按鈕、小按鈕(style="?android:attr/buttonStyleSmall")與開關按鈕(ToggleButton)。這裡有個值得學的技巧:用 style="?android:attr/... 而非 @style/,代表引用的是「當前主題」中的樣式定義,換主題時會自動跟著變。
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Regular sized buttons -->
<Button android:id="@+id/button_normal"
android:text="@string/buttons_1_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!-- Small buttons -->
<Button android:id="@+id/button_small"
style="?android:attr/buttonStyleSmall"
android:text="@string/buttons_1_small"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ToggleButton android:id="@+id/button_toggle"
android:text="@string/buttons_1_toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

Chronometer 是個相當省事的小控制項,版面只要一行:
<Chronometer android:id="@+id/chronometer"
android:format="@string/chronometer_initial_format"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="0" android:paddingBottom="30dip"
android:paddingTop="30dip" />
<Button android:id="@+id/start" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/chronometer_start">
<requestFocus />
</Button>
程式端掛上五個監聽器:
button = (Button) findViewById(R.id.start);
button.setOnClickListener(mStartListener);
button = (Button) findViewById(R.id.stop);
button.setOnClickListener(mStopListener);
button = (Button) findViewById(R.id.reset);
button.setOnClickListener(mResetListener);
button = (Button) findViewById(R.id.set_format);
button.setOnClickListener(mSetFormatListener);
button = (Button) findViewById(R.id.clear_format);
button.setOnClickListener(mClearFormatListener);
各監聽器的行為:
View.OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.start();
}
};
View.OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.stop();
}
};
View.OnClickListener mResetListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.setBase(SystemClock.elapsedRealtime());
}
};
View.OnClickListener mSetFormatListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.setFormat("Formatted time (%s)");
}
};
View.OnClickListener mClearFormatListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.setFormat(null);
}
};
兩個重點:setBase() 傳入 SystemClock.elapsedRealtime() 才是歸零重置;setFormat() 裡的 %s 會被實際時間字串取代,傳 null 則回到預設格式。


星號 CheckBox 用了 style="?android:attr/starStyle",讓外觀跟隨主題。
<CheckBox android:id="@+id/star"
style="?android:attr/starStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/controls_1_star" />
接著示範四種文字色彩與分隔線樣式:

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:text="@string/textColorPrimary"
android:textAppearance="?android:attr/textAppearanceLarge"
android:focusable="true"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:text="@string/textColorSecondary"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="?android:attr/textColorSecondary"
android:focusable="true"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:text="@string/textColorTertiary"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="?android:attr/textColorTertiary"
android:focusable="true"
/>
<TextView
style="?android:attr/listSeparatorTextViewStyle"
android:text="@string/listSeparatorTextViewStyle"
android:layout_marginTop="5dip"
/>
這一段的價值在於示範「主題屬性引用」的用法:textAppearanceLarge 同時帶入字級與字型,textColorPrimary / Secondary / Tertiary 對應三層視覺主次,而 listSeparatorTextViewStyle 直接借用清單分隔線的樣式。全部用 ?android:attr/ 而非寫死數值,換主題時整組畫面會自動調整——這是寫出可被客製化應用程式的關鍵習慣。
從生活比喻理解 Android 執行緒與訊息佇列
用隧道與汽車理解訊息佇列如果把 Android 的訊息佇列想像成一條隧道,那麼每一輛進入隧道的汽車就像一則等待處理的訊息。在這個比喻裡,先進入隧道的車輛會先離開,這正是先
Android ApiDemo 圖形與視圖(四):ListView 效能優化與 ProgressBar 全解
本篇繼續整理 ApiDemo「Graphics and Views」第 58 到 69 號範例,主題集中在兩塊:一是 ListView 的選擇模式與高效 Adapter
Android 開發講義(二):DDMS 模擬簡訊、Layout 的服務觀與繼承/委託抉擇
八、如何從 DDMS 發送簡訊給應用程式 切換到 DDMS 路徑一:在 Eclipse 的 Android 程式編輯畫面,點擊右上角的 DDMS 按鈕,再從清單中選取即可
Android 開發講義(五):IBinder 安全性與跨進程 Activity 溝通
十三、IBinder 介面與它的安全機制 Activity 物件與 Service 物件通常執行在不同的 process 裡,各有不同的 UID。因為彼此獨立,Activ