編輯:關於 Android 程式設計
儘管 Android 已提供 Button、ImageView、TextView、EditText 等豐富控制項,但在實際專案中,仍常需要開發者自訂可重複使用的控制項,讓它能像系統控制項一樣方便使用。所幸 Android 為自訂控制項提供了完整的基礎類別(如 View、Canvas)與 XML 標籤(如 declare-styleable、attr),讓整個過程有章可循。
一、在 values 目錄建立名為 attrs 的 XML 檔
外層的 <declare-styleable name="CustomView"> 讓自訂 View 擁有自身屬性,裡面定義了 textString(顯示文字)、colorValue(字體顏色)、textSize(字體大小)三個屬性,使用起來就像設定 TextView 的 textSize、textColor 一樣直觀。
為何 declare-styleable 的 name 要與自訂 View 的類別名一致?依 Google 文件的說法,這是慣例:雖然並非強制,但許多熱門程式碼編輯器依賴這個命名慣例來提供程式碼自動補全。
二、編寫佈局文件並引用自訂 View
此處有兩個重點:
https://schemas.android.com/apk/res/android,而屬於 https://schemas.android.com/apk/res/[你的套件名稱],所以要加上 xmlns:app="https://schemas.android.com/apk/res/com.project.summary"。<com.project.summary.customview.CustomView。若 CustomView 是 ParentCustomView 的內部類,則需寫成 <com.project.summary.customview.ParentCustomView$CustomView,中間以 $ 連接。設定自訂屬性時前面要加 app 前綴。三、編寫自訂 View 程式碼
Google 文件要求自訂 View 至少要有一個以 Context 與 AttributeSet 為參數的建構子,原因有二:其一,讓 layout editor 能創建與編輯你的 View;其二(也是主因),當 View 從 XML 佈局創建時,標籤中的所有屬性會被讀進資源包並以 AttributeSet 傳入建構子,接著可用 obtainStyledAttributes() 把屬性轉成 TypedArray 陣列,再以預定義常量輕鬆讀取。
public class CustomView extends View {
private int color;
private String mText;
private int textSize;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
try {
mText = a.getString(R.styleable.CustomView_textString);
color = a.getColor(R.styleable.CustomView_colorValue, R.color.textRed);
textSize = a.getDimensionPixelOffset(R.styleable.CustomView_textSize, 20);
} finally {
a.recycle(); // 記得回收 TypedArray
}
}
}
可以用 TypedArray 提供的相關方法取出佈局中設定的屬性,別忘了最後要回收。
四、完整示例
本例自訂了一個用來顯示文字的 View,功能類似 TextView(由於本文聚焦於自訂 View 的創建與使用,功能細節從略):
public class CustomView extends View {
private int color;
private Paint mTextPaint;
private String mText;
private int textSize;
private int mAscent;
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
initLabelView();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
try {
mText = a.getString(R.styleable.CustomView_textString);
color = a.getColor(R.styleable.CustomView_colorValue, R.color.textRed);
if (mText != null) {
setCustomText(mText);
}
setTextColor(color);
textSize = a.getDimensionPixelOffset(R.styleable.CustomView_textSize, 20);
if (textSize > 0) {
setTextSize(textSize);
}
} finally {
a.recycle();
}
}
private void setCustomText(String text) {
mText = text;
requestLayout();
invalidate();
}
private final void initLabelView() {
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
// 手動縮放文字大小以符合螢幕密度
mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
mTextPaint.setColor(0xFF000000);
setPadding(3, 3, 3, 3);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = (int) mTextPaint.measureText(mText) + getPaddingLeft() + getPaddingRight();
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
private int measureHeight(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
mAscent = (int) mTextPaint.ascent();
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = (int) (-mAscent + mTextPaint.descent()) + getPaddingTop() + getPaddingBottom();
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
public void setTextSize(int size) {
mTextPaint.setTextSize(size);
requestLayout();
invalidate();
}
public void setTextColor(int color) {
mTextPaint.setColor(color);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent, mTextPaint);
}
}
<attr name="background" format="reference" /><attr name="textColor" format="color" /><attr name="focusable" format="boolean" /><attr name="customWidth" format="dimension" /><attr name="fromAlpha" format="float" /><attr name="frameDuration" format="integer" /><attr name="textString" format="string" /><attr name="pivotX" format="fraction" />掌握 attrs 定義、命名空間設定、以 obtainStyledAttributes 讀取屬性,以及 onMeasure/onDraw 的重寫,就能打造出具備自訂屬性、可在 XML 中靈活使用的自訂控制項。
Android DNS 解析流程簡析
Android 的 DNS 相關程式碼主要位於 bionic/libc/netbsd 目錄中。雖然 netbsd 已不是活躍專案,但其中的 DNS 解析部分仍被 Andr
Android進度條設計詳解:條形進度條與圓形Loading動畫
Android進度條可分為條形與圓形。條形進度條可用ProgressBar搭配自訂style與shape,透過layer-list設定背景、進度與圓角。 圓形Loadin
Firebase 上手 for Android:分析、用戶認證與實時數據庫
移動應用要做大一點,幾乎繞不開後端:用戶身份驗證、多設備數據同步、行為統計。可自建服務器意味著要懂運維、懂數據庫、懂接口設計——而多數獨立開發者的技能樹恰好缺這一支。 好
用 WindowManager 在應用最上層繪製懸浮 View
一般來說,Android 顯示一個 View 都是透過 Activity 的 setContentView 來設定。但其實還有一條路:直接用 WindowManager