編輯:關於 Android 程式設計
Android 允許開發者自訂 View 元件,並直接於版面配置檔中引用。本文示範如何在 layout.xml 中使用全限定類別名稱來載入自訂的 View,並以一個會定時切換圖片的 GGView3 為例說明其內部實作。
只要在 XML 中寫入自訂 View 的完整類別路徑,Android 便會在解析版面時自動實例化它:
<com.bn.summer.GGView3
android:layout_width="100dip"
android:layout_height="114dip"
android:layout_marginLeft="11dip" />
此 View 繼承自 View,建構子中必須接收 Context 與 AttributeSet,這是為了讓系統能從 XML 正確實例化。範例在內部啟動了一個執行緒,每隔一段時間切換要繪製的圖片並呼叫 postInvalidate 觸發重繪。
package com.bn.summer;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class GGView3 extends View {
int COMPONENT_WIDTH;
int COMPONENT_HEIGHT;
boolean initflag = false;
Bitmap[] bma;
Paint paint;
int[] drawablesId;
int currIndex = 0;
boolean workFlag = true;
public GGView3(Context father, AttributeSet as) {
super(father, as);
this.drawablesId = new int[] {
R.drawable.room1,
R.drawable.room2,
R.drawable.room3,
};
bma = new Bitmap[drawablesId.length];
initBitmaps();
paint = new Paint();
paint.setFlags(Paint.ANTI_ALIAS_FLAG); // 消除鋸齒
new Thread() {
public void run() {
while (workFlag) {
currIndex = (currIndex + 1) % drawablesId.length;
GGView3.this.postInvalidate();
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
public void initBitmaps() {
Resources res = this.getResources();
for (int i = 0; i < drawablesId.length; i++) {
bma[i] = BitmapFactory.decodeResource(res, drawablesId[i]);
}
}
public void onDraw(Canvas canvas) {
if (!initflag) {
COMPONENT_WIDTH = this.getWidth(); // 取得 view 的寬度
COMPONENT_HEIGHT = this.getHeight(); // 取得 view 的高度
initflag = true;
}
int picWidth = bma[currIndex].getWidth();
int picHeight = bma[currIndex].getHeight();
int startX = (COMPONENT_WIDTH - picWidth) / 2;
int startY = (COMPONENT_HEIGHT - picHeight) / 2;
// 繪製背景色
canvas.drawARGB(255, 200, 128, 128);
canvas.drawBitmap(bma[currIndex], startX, startY, paint);
}
}
幾個重點:自訂 View 若要在 XML 中使用,務必提供接收 AttributeSet 的建構子;在 onDraw 中首次取得元件寬高後以旗標記錄,避免重複計算;而更新畫面時應透過 postInvalidate 而非直接在子執行緒操作 UI,以確保執行緒安全。
用 ContentObserver 實現 Android 短信驗證碼自動填充
做過註冊登錄流程的人大概都熟悉這個場景:點下「獲取驗證碼」,短信很快進來,可 App 並不會幫你填,你得切到短信介面記住那六位數字,再切回來一個一個敲進輸入框。來回折騰幾
Android 單選與多選對話框實現代碼詳解
「請選擇性別」用單選,「你最喜歡哪些城市」用多選——這兩種對話框在 Android 裡都由 AlertDialog.Builder 直接提供,無需自定義佈局。核心就是兩個
Android 序列化詳解:Serializable 與 Parcelable 全面對比
本文將系統講解 Android 中 Serializable 與 Parcelable 兩種序列化方式的原理、用法與性能差異,幫助你在開發中做出正確選擇。 一、為什麼要序
Android 自定義 Toast:從 WindowManager 原理到可客製提示
Toast 是 Android 中常見的輕量提示元件,使用簡單,但樣式較為單一。若開發者希望自定義顯示內容、外觀或顯示時機,可以從其底層實現著手,理解 Toast 是如何