萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 自訂屬性 format 完整解析:reference、color、dimension、enum、flag 等 10 種類型實戰

前言

在 `res/values/attrs.xml` 中宣告 `` 時,`format` 決定屬性值的解析類型與編譯期檢查。本文詳細列舉 10 種核心 format 類型的定義語法、XML 使用範例、程式碼取值 API 及常見陷阱。

10 種 Format 類型詳解

1. reference — 資源 ID 參考

<attr name="customBackground" format="reference" />
<View
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:customBackground="@drawable/my_bg" />
// 取值
int resId = a.getResourceId(R.styleable.MyView_customBackground, 0);
Drawable bg = a.getDrawable(R.styleable.MyView_customBackground);

可參考:`@drawable/...`、`@color/...`、`@layout/...`、`@string/...` 等任意資源類型。

2. color — 顏色值

<attr name="titleTextColor" format="color" />
<TextView
    app:titleTextColor="#FF5722"
    app:titleTextColor="@color/brand_primary" />
int color = a.getColor(R.styleable.MyView_titleTextColor, Color.BLACK);
// 或取得 ColorStateList (支援 selector)
ColorStateList csl = a.getColorStateList(R.styleable.MyView_titleTextColor);

支援 `#RGB`、`#ARGB`、`#RRGGBB`、`#AARRGGBB`、資源引用、Theme 屬性 `?attr/colorPrimary`。

3. boolean — 布林值

<attr name="enableAnimation" format="boolean" />
<View app:enableAnimation="true" />
boolean enabled = a.getBoolean(R.styleable.MyView_enableAnimation, false);

4. dimension — 尺寸值 (含單位)

<attr name="cornerRadius" format="dimension" />
<View app:cornerRadius="8dp" />
<View app:cornerRadius="12sp" />
<View app:cornerRadius="2px" />
// 回傳 px (已換算)
float px = a.getDimension(R.styleable.MyView_cornerRadius, 0f);
// 回傳原始 dp/sp 值 (較少用)
float raw = a.getDimensionPixelSize(R.styleable.MyView_cornerRadius, 0);
int dp = a.getDimensionPixelOffset(R.styleable.MyView_cornerRadius, 0);

**注意**:`getDimension()` 回傳已換算為 px 的浮點數;`getDimensionPixelSize()` 回傳四捨五入後的 px 整數;`getDimensionPixelOffset()` 用於邊距/偏移 (可為負)。

5. float — 浮點數

<attr name="progress" format="float" />
<View app:progress="0.75" />
float value = a.getFloat(R.styleable.MyView_progress, 0f);

6. integer — 整數

<attr name="maxCount" format="integer" />
<View app:maxCount="100" />
int value = a.getInteger(R.styleable.MyView_maxCount, 0);

也可用於枚舉整數值 (但建議用 `enum`)。

7. string — 字串

<attr name="apiKey" format="string" />
<com.example.MapView
    app:apiKey="AIzaSy..." />
String key = a.getString(R.styleable.MapView_apiKey);

支援字串資源引用 `@string/...`、轉義字元。

8. fraction — 百分比/分數 (相對父容器尺寸)

<attr name="pivotX" format="fraction" />
<attr name="pivotY" format="fraction" />
<RotateDrawable
    app:pivotX="50%"
    app:pivotY="50%" />
// 取值為 0.0~1.0 (或超過 1.0)
float fraction = a.getFraction(R.styleable.RotateDrawable_pivotX, 1, 1, 0.5f);
// 參數:attrId, baseWidth, baseHeight, defaultValue
// 實際像素 = fraction * baseWidth (或 baseHeight)

常用於 `pivotX/Y`、`translateX/Y` 等相對尺寸屬性。

9. enum — 枚舉 (單選)

<attr name="orientation">
    <enum name="horizontal" value="0" />
    <enum name="vertical" value="1" />
</attr>
<LinearLayout
    android:orientation="vertical" />
int value = a.getInt(R.styleable.LinearLayout_orientation, 0);
// 對應 enum 的 value (0 或 1)

**優點**:編譯期限制合法值、XML 提示自動完成、程式碼可用 `switch` 明確處理。

10. flag — 位元旗標 (多選,按位或運算)

<attr name="windowSoftInputMode">
    <flag name="stateUnspecified" value="0" />
    <flag name="stateHidden" value="1" />
    <flag name="stateVisible" value="2" />
    <flag name="adjustResize" value="0x10" />
    <flag name="adjustPan" value="0x20" />
</attr>
<activity
    android:windowSoftInputMode="stateHidden|adjustResize" />
int flags = a.getInt(R.styleable.Activity_windowSoftInputMode, 0);
// 檢查特定旗標
boolean adjustResize = (flags & 0x10) != 0;

**關鍵**:`value` 必須是 2 的冪次 (1, 2, 4, 8, 0x10, 0x20...),以便按位組合。

進階:混合格式與自訂類型

<!-- 支援 reference | color 雙重格式 -->
<attr name="background" format="reference|color" />

程式碼取值時需按優先序嘗試:

Drawable bg = a.getDrawable(id);
if (bg == null) {
    int color = a.getColor(id, 0);
    bg = new ColorDrawable(color);
}

完整 attrs.xml 範例

<resources>
    <declare-styleable name="CustomCardView">
        <attr name="cardBackground" format="reference|color" />
        <attr name="cardCornerRadius" format="dimension" />
        <attr name="cardElevation" format="dimension" />
        <attr name="cardTitleText" format="string" />
        <attr name="cardTitleColor" format="color" />
        <attr name="cardActionEnabled" format="boolean" />
        <attr name="cardProgress" format="float" />
        <attr name="cardMaxItems" format="integer" />
        <attr name="cardPivotX" format="fraction" />
        <attr name="cardGravity">
            <enum name="start" value="0" />
            <enum name="center" value="1" />
            <enum name="end" value="2" />
        </attr>
        <attr name="cardFlags">
            <flag name="clickable" value="1" />
            <flag name="focusable" value="2" />
            <flag name="longClickable" value="4" />
        </attr>
    </declare-styleable>
</resources>

取值最佳實踐:TypedArray Recycle 模式

public CustomCardView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomCardView);
    try {
        // 依序取值...
        background = a.getDrawable(R.styleable.CustomCardView_cardBackground);
        cornerRadius = a.getDimensionPixelSize(R.styleable.CustomCardView_cardCornerRadius, 0);
        // ...
    } finally {
        a.recycle(); // 必須釋放,避免記憶體洩漏
    }
}

總結

精準選擇 `format` 類型,能讓自訂 View 在 XML 中獲得**型別安全、自動完成提示、編譯期錯誤檢查**,並在程式碼中以正確 API 取得已換算/解析的值。核心口訣:引用用 reference、顏色用 color、尺寸用 dimension、比例用 fraction、單選用 enum、多選用 flag、數值用 integer/float、文字用 string。

copyright © 萬盛學電腦網 all rights reserved