Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 自訂元件:從擴展 View 到自訂屬性

編輯:進階開發

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() 等方法都能用來繪製你的元件。

完成自訂元件後,有兩種方式可以在應用程式中把它實例化。

方式一:在 Activity 中以程式碼建立

寫法與實例化內建元件完全相同:

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DateView dateView = new DateView(this); setContentView(dateView); }

方式二:在布局 XML 中宣告

概念與使用內建元件無異,只要把標籤名稱換成自訂元件的完整類別名稱即可。以下範例假設 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 開始在專案各處複製貼上時,就是該把它抽成自訂元件的時機。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved