編輯:進階開發
Android 內建了 Button、TextView、EditText、ListView、CheckBox、RadioButton、Gallery、Spinner、AutoCompleteTextView 等現成元件,足以應付絕大多數情境。但仍會遇到需求超出既有元件能力的時候——這時就該打造自己的自訂元件。
如果只是想把現有元件或布局稍微調整一下,最簡單的做法就是繼承它、覆寫需要改的方法。這樣一來你能精準控制元素的外觀與行為,又不必放棄父類別已經寫好的功能。
最省事的路子是擴展現有的 widget 類別;若現有理元件都不合用,再直接從 android.view.View 開始繼承。
在最簡單的形式下,你只需要為基底類別的每個建構子各寫一個對應的建構子。以下以擴展 TextView 建立一個 DateView 為例,三個建構子都要備齊:
public class DateView extends TextView { public DateView(Context context) { super(context); //--- Additional custom code -- } public DateView(Context context, AttributeSet attrs) { super(context, attrs); //--- Additional custom code -- } public DateView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); //--- Additional custom code -- } }
寫完之後,DateView 就完整繼承了 TextView 的所有屬性、方法與事件,可以直接使用而無需額外實作。接下來只要把你自己的邏輯補進去即可。
如果你需要自行繪製外觀或調整元件尺寸,則要覆寫 onMeasure(int widthMeasureSpec, int heightMeasureSpec) 與 onDraw(Canvas canvas)。反之,若只是沿用內建元件的外觀,這兩個方法完全不必碰。
其中 onMeasure() 是布局管理器用來詢問尺寸的回呼,你必須在裡面呼叫 setMeasuredDimension(int width, int height) 回報計算結果。
而 onDraw() 則是實際作畫的地方,其中的 android.graphics.Canvas 與 Swing 的 Canvas 概念相當接近,drawRect()、drawLine()、drawString()、drawBitmap() 等方法都能用來繪製你的元件。
完成自訂元件後,有兩種方式可以在應用程式中把它實例化。
寫法與實例化內建元件完全相同:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DateView dateView = new DateView(this); setContentView(dateView); }
概念與使用內建元件無異,只要把標籤名稱換成自訂元件的完整類別名稱即可。以下範例假設 DateView 位於 com.yiibai.dateviewdemo 套件中:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <com.yiibai.dateviewdemo.DateView android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#fff" android:textSize="40sp" android:background="#000" /> </RelativeLayout>
值得注意的是,這裡用到的屬性全是 TextView 的既有屬性,自訂元件完全無需改動。同理,DateView 也能使用所有繼承而來的方法與事件。
前面的例子雖然擴展了功能,但用的都還是父類別的屬性。如果我們想從頭設計自己的屬性呢?以下示範新增 delimiter(分隔字元)與 fancyText(是否套用特殊樣式)兩個屬性,並在布局中這樣使用:
<com.yiibai.dateviewdemo.DateView android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#fff" android:textSize="40sp" custom:delimiter="-" custom:fancyText="true" />
先在 res/values/ 目錄下建立 attrs.xml 來定義這些屬性:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="DateView"> <attr name="delimiter" format="string"/> <attr name="fancyText" format="boolean"/> </declare-styleable> </resources>
其中 name 就是布局檔中要使用的屬性名稱,format 則是該屬性的型別。
接著要在元件類別中把這些屬性讀出來。由於 XML 屬性會透過帶有 AttributeSet 參數的建構子傳入,因此邏輯寫在那裡最合適。做法是先用 AttributeSet 建立一個 TypedArray,再逐一讀值:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DateView); final int N = a.getIndexCount(); for (int i = 0; i < N; ++i) { int attr = a.getIndex(i); switch (attr) { case R.styleable.DateView_delimiter: String delimiter = a.getString(attr); // ...do something with delimiter... break; case R.styleable.DateView_fancyText: boolean fancyText = a.getBoolean(attr, false); // ...do something with fancyText... break; } } a.recycle();
別忘了最後呼叫 recycle() 釋放資源。
最後,在布局檔中加上自訂命名空間宣告,就能使用這些屬性了:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" xmlns:custom="https://schemas.android.com/apk/res/com.yiibai.dateviewdemo" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <com.yiibai.dateviewdemo.DateView android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#fff" android:textSize="40sp" custom:delimiter="-" custom:fancyText="true" /> </RelativeLayout>
關鍵在於 xmlns:custom="https://schemas.android.com/apk/res/com.yiibai.dateviewdemo" 這一行。固定前綴 https://schemas.android.com/apk/res/ 保持不變,最後一段要換成你的套件名稱;至於 custom 這個前綴名稱則可以任取,改成任何你喜歡的字都可以。
自訂元件真正好用之處,在於它把「一個畫面上重複出現的複合元件」封裝成可重複使用、可參數化的單位。當同一組 UI 開始在專案各處複製貼上時,就是該把它抽成自訂元件的時機。
SurfaceView 繪圖攻略:覆蓋刷新與髒矩形刷新實作
在 Android 上做遊戲,SurfaceView 幾乎是標配。它最大的好處是擁有獨立的繪圖表面,可以在自己的執行緒裡不停重畫,不必受 View 單執行緒模型拖累。以下
為什麼說 Android 令人沮喪(一)
這段時間,隨著 Moto 的一系列手機引爆了 Android 市場,行動市場所有的目光都集中在這顆新星之上。一時之間,無論晶片企業、設備企業、軟體企業還是網際網路企業都表
Eclipse 搭配 ADT 開發 Android 的常見問題與解法
近來用 Eclipse 搭配 ADT 開發 Android,感覺 bug 還真不少,問題甚至比 Symbian 更多,反倒讓人體會到微軟在開發者體驗上的用心。Eclips
新一代 Android 手機巡禮:摩托羅拉 OpusOne 與開放源碼聯盟
Android 手機將成為谷歌手機主導的開發平台,最終成為 Android 生態的主要成員,這對諾基亞的 Symbian 與微軟的 Windows Mobile 都帶來了