編輯:Android 開發實例
上一篇我們把自訂 View 的基本寫法走過一遍,這一篇要往前推進一步——讓我們自己寫的元件也能像官方控制項那樣,在 XML 裡配置屬性。
如果你還沒看過前一課,建議先補上《Android 高手進階教程(三)》,兩篇連著讀會順很多。
寫布局時我們早就習慣了 android:text=""、android:textColor="" 這類寫法。那麼,能不能替自己的元件也開一組屬性,寫成 test:attrs="" 的樣子?答案是可以的。而且這一步往往是自訂元件從「能跑」走向「好用」的分水嶺。
整個流程可以拆成四個環節:宣告屬性 → 在構造方法中用 TypedArray 取值 → 在布局裡掛上命名空間前綴 → 編譯執行驗證。
先在 res/values 目錄建立一個 attrs.xml,用 <declare-styleable> 標籤把屬性打包成一個「樣式集合」:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
這裡有兩個關鍵點。第一,name="MyView" 是這個樣式集合的名字,後面在 Java 程式碼裡取屬性會用到它。第二,format 用來約束屬性的值類型,常見的有 color、dimension、string、boolean、integer、reference 等等;寫對 format,才能在程式碼裡呼叫對應的 getColor()、getDimension() 這類方法。
真正的重點在「帶有 AttributeSet 參數的那個構造方法」。當元件是透過 XML 布局被 inflate 出來的時候,系統呼叫的就是這一個建構子,屬性值也只能在這裡拿到。
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF);
float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
mPaint.setTextSize(textSize);
mPaint.setColor(textColor);
a.recycle();
}
幾個容易踩坑的細節:
R.styleable.MyView 對應的是 attrs.xml 裡 <declare-styleable name="MyView"> 的名字。R.styleable.MyView_textColor。這個常數會由 aapt 自動產生,寫錯名字編譯不會過。getColor()、getDimension() 的第二個參數是預設值。一旦布局裡沒有寫這個屬性,就會退回預設值,這能有效避免空值造成的異常。本例中顏色預設不透明白色,字級預設 36。TypedArray 一定要呼叫 recycle()。這是為了讓資源能被後續的屬性讀取重複利用,養成習慣比較保險。package com.android.tutor;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
private Paint mPaint;
private Context mContext;
private static final String mString = "Welcome to Mr Wei's blog";
public MyView(Context context) {
super(context);
mPaint = new Paint();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF);
float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
mPaint.setTextSize(textSize);
mPaint.setColor(textColor);
a.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 設定為填滿樣式
mPaint.setStyle(Style.FILL);
// 畫一個矩形,前兩個數字是左上角座標,後兩個是右下角座標
canvas.drawRect(new Rect(10, 10, 100, 100), mPaint);
mPaint.setColor(Color.BLUE);
// 繪製文字
canvas.drawText(mString, 10, 110, mPaint);
}
}
值得留意的是:在 onDraw() 裡我們把畫筆顏色又改回藍色,所以自訂屬性 textColor 實際影響的是矩形填色,文字顏色則被程式碼覆蓋了。這是原作者的示範寫法,自己在實作時記得釐清「哪個屬性控制哪個圖形」。
要在布局中使用自訂屬性,必須先在根節點宣告命名空間:
xmlns:test="https://schemas.android.com/apk/res/com.android.tutor"
其中 test 是自訂的前綴,名稱可以隨意取;後面那段 URI 則固定是 https://schemas.android.com/apk/res/ 再加上你的應用套件名稱。這也是為什麼自訂屬性寫起來會是 test:textSize 這種形式。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:test="https://schemas.android.com/apk/res/com.android.tutor"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<com.android.tutor.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
test:textSize="20px"
test:textColor="#fff"
/>
</LinearLayout>
跑起來之後,畫面上會出現一個矩形與一行文字。此時試著改動 test:textSize 與 test:textColor 的值,重新執行,你會看到矩形的大小與顏色跟著改變——這就代表自訂屬性已經完整打通了。再把這兩個屬性整行刪掉執行一次,矩形會退回預設的白色、36 的字級,這正好驗證了預設值機制也生效。
自訂屬性的核心其實只有三件事:在 attrs.xml 宣告、在帶 AttributeSet 的建構子裡用 TypedArray 取值、在布局中宣告命名空間前綴。把這三步練熟,你就能開始包裝出真正可重複使用、可交由設計人員在 XML 裡微調的自家元件庫。
有疑問歡迎留言討論。
Android JSON 資料解析:天氣 API 實作範例
JSON 解析在 Android 中常用於 API 回傳。本文以天氣資料為例,說明如何從 JSON 字串取出溫度、濕度與氣壓。 四個常用類別 JSONArray 處理陣列
Android ListView 常見用法實戰:從默認布局到多選與點擊響應
ListView 是列表展示的首選控件(在 RecyclerView 普及之前更是如此)。本文用一套由淺入深的示例,把它的三要素、默認布局、多選模式與事件響應串起來講。
Android 網絡圖片查看顯示的實現方法
很多應用都需要從網路載入圖片並顯示。常見做法是在介面中放置輸入框、按鈕與 ImageView,當使用者輸入圖片網址並點擊按鈕後,再於背景執行緒中下載圖片資料。關鍵流程下載
Android 實作 Market 風格的 Loading 效果:自訂版面取代 ProgressDialog
在 Android 裡做載入提示,直覺做法是 ProgressDialog。ApiDemos 中的 ProgressBar3.java 就示範了兩種典型用法:但仔細看 A