Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自訂 Android Button 控件:七個實作要點

編輯:關於 Android 程式設計

當標準 Button 無法滿足需求時,繼承 Button 自行繪製是常見解。以下七點是實作自訂按鈕時會用到的關鍵技巧。

1. 不必另外定義 Listener

直接呼叫 performClick(),內部會觸發 View.OnClickListener,這也是自訂 View 提供「可被點擊」語意的標準做法。

2. 正確轉型成 BitmapDrawable

放在 res/drawable 中的 png、gif 等圖形資源,載入時實際都是 BitmapDrawable 物件。若要自繪,應該直接轉型以便調用 drawBitmap():

mIconAccept = (BitmapDrawable) context.getResources()
        .getDrawable(R.drawable.latebutton_ok);

3. 用 getIntrinsicWidth/Height 取尺寸

圖片實際尺寸可能與資源檔標示的不同,程式碼中應透過下列方法取得真實長寬,而不是寫死數字:

mIconAccept.getIntrinsicWidth()
mIconAccept.getIntrinsicHeight()

4. 繼承 Button 會更方便

相對於直接繼承 View 從零繪製,繼承 Button 可以沿用系統的樣式、padding 計算與無障礙屬性,多數情況省事不少。

5. 複用既有屬性

不必急著自訂 attribute,Android 現成的 android:text 就能勝任。在 XML 中宣告:

<com.friendlocation.LateButton
    android:id="@+id/lateButton1"
    android:layout_width="300dp"
    android:layout_height="36dp"
    android:text="查詢" />

並在建構子中讀取。注意 namespace 要寫完整網址,不能只寫 android:

public LateButton(Context context, AttributeSet attrs) {
    super(context, attrs);

    mText = attrs.getAttributeValue(
            "https://schemas.android.com/apk/res/android", "text");
    if (mText == null) mText = "Default Text";
}

6. 區分編輯模式

Layout Editor 預覽時也會呼叫自訂 View 的建構子。若此時去載入資源或做耗時運算,會拖慢預覽甚至讓編輯器報錯。用 isInEditMode() 隔開即可:

public LateButton(Context context, AttributeSet attrs) {
    super(context, attrs);
    if (!this.isInEditMode()) {
        mIconAccept = (BitmapDrawable) context.getResources()
                .getDrawable(R.drawable.latebutton_icon);
    }
}

7. 走訪全部屬性

若不確定 XML 裡有哪些屬性,可以逐一列印出來除錯:

for (int i = 0; i < attrs.getAttributeCount(); i++) {
    String name = attrs.getAttributeName(i);
    String value = attrs.getAttributeValue(i);
    if (name.equals("text"))
        mText = value;
}

這七點合起來,基本涵蓋了一個實用自訂按鈕所需的要素:資源轉型、尺寸取得、屬性解析、編輯模式相容與點擊回饋。

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