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

Android 自定義 View(二):把自定義屬性從定義到解析講透

編輯:關於 Android 程式設計

這一篇要把自定義屬性的完整流程走通:屬性從哪來、為什麼要自己定義、format 有哪些取值、以及如何在校件裡把它解析出來。

一、為什麼需要自定義屬性

使用屬性的前提,是這個屬性必須先存在。我們寫佈局文件時從未自己定義過屬性,卻能大量使用 android: 開頭的配置,原因很簡單:系統早已幫我們定義好了。

系統屬性可以在 \sdk\platforms\android-xx\data\res\values\attrs.xml 中找到,裡面是一份相當長的清單:

<declare-styleable name="View">
    <attr name="id" format="reference">
    <attr name="background" format="reference|color">
    <attr name="padding" format="dimension">
    ...
    <attr name="focusable" format="boolean">
</declare-styleable>

<declare-styleable name="TextView">
    <attr name="text" format="string" localization="suggested">
    <attr name="hint" format="string">
    <attr name="textColor">
    ...
</declare-styleable>

<declare-styleable name="ViewGroup_Layout">
    <attr name="layout_width" format="dimension">
        <enum name="match_parent" value="-1">
        <enum name="wrap_content" value="-2">
    </attr>
    <attr name="layout_height" format="dimension"> ... </attr>
</declare-styleable>

<declare-styleable name="LinearLayout_Layout">
    <attr name="layout_weight" format="float">
    <attr name="layout_gravity">
</declare-styleable>

<declare-styleable name="RelativeLayout_Layout">
    <attr name="layout_centerInParent" format="boolean">
    ...
</declare-styleable>

仔細觀察會發現,這些屬性是以 declare-styleable 為單位分組的,每組有一個 name 用來標明歸屬:View 這組是給所有 View 用的,TextView 這組是給 TextView 用的。

由於所有控件都是 View 的後代,凡是掛在 View 名下的屬性,任何控件都能直接使用——這正是我們的自定義控件一個屬性都沒寫,卻能吃到一堆系統屬性的原因。

但並非所有屬性都通用。TextView 作為 View 的子類,既能用 View 的屬性,也能用專屬於自己的 android:text;反過來,純 View 寫 android:text 是無效的。同理,layout_weight 是為 LinearLayout 的 LayoutParams 定製的,RelativeLayout 裡寫了也不會生效。

結論很清楚:自定義控件若不自己擴展屬性,就只能沿用 View 那一層的通用配置。想要讓自己的控件擁有獨立的可配置項,就必須動手定義。

二、如何定義屬性

翻閱系統的 attrs 文件會發現兩種寫法,區別就在於 attr 標籤是否帶 format:帶 format 的是定義一個新屬性,不帶 format 的是引用已有屬性。而 format 的作用是限定這個屬性能接受哪種類型的值。

假設我們的自定義控件也需要一個文本屬性,有兩條路可選。

第一種:完全自己定義一個新屬性(名字可以自定,比如 text 或 mText)

<resources>
    <declare-styleable name="MyTextView">
        <attr name="mText" format="string" />
    </declare-styleable>
</resources>

第二種:直接引用系統已有的 text 屬性(注意必須加上 android 命名空間,系統才知道你指的是它那一個)

<resources>
    <declare-styleable name="MyTextView">
        <attr name="android:text" />
    </declare-styleable>
</resources>

為什麼系統明明定義了 text,我們使用時還要在自己的 styleable 中聲明一次?因為系統的 text 是掛在 TextView 名下的,不聲明,我們的控件就拿不到它。

三、屬性值類型 format 全覽

format 一共支持 11 種取值。

1. reference:引用某個資源 ID

<attr name="background" format="reference" />

使用:<ImageView android:background="@drawable/pic" />

2. color:顏色值

使用:<TextView android:textColor="#00FF00" />

3. boolean:布爾值

使用:<Button android:focusable="true" />

4. dimension:尺寸值

使用:<Button android:layout_width="42dip" />

5. float / 6. integer:浮點數與整數

使用:<attr name="layout_weight" format="float" />

7. string:字符串

使用:<TextView android:text="我是文本" />

8. fraction:百分比

使用:<Rotate android:pivotX="200%" />

9. enum:枚舉

<declare-styleable name="MyView">
    <attr name="orientation">
        <enum name="horizontal" value="0" />
        <enum name="vertical" value="1" />
    </attr>
</declare-styleable>

使用:<LinearLayout android:orientation="vertical" />

枚舉型屬性每次只能選其中一個值,不能寫成 android:orientation="horizontal|vertical"。

10. flag:位或運算

<declare-styleable name="MyView">
    <attr name="gravity">
        <flag name="top" value="0x30" />
        <flag name="bottom" value="0x50" />
        <flag name="left" value="0x03" />
        <flag name="right" value="0x05" />
        <flag name="center_vertical" value="0x10" />
    </attr>
</declare-styleable>

使用:<TextView android:gravity="bottom|left" />。與枚舉相反,flag 可以多值組合。

11. 混合類型

允許一個屬性同時接受多種類型,最典型的就是 background:

<attr name="background" format="reference|color" />

使用時既可以寫 @drawable/pic,也可以寫 #00FF00。

四、命名空間與在代碼中取值

佈局文件裡每個屬性前面的 android: 前綴,對應的是文件頭部引入的命名空間 xmlns:android="https://schemas.android.com/apk/res/android",它告訴 XML 解析器該去哪裡找這個屬性的出處。

同理,自定義屬性存放在我們自己的應用包中,需要引入應用包的命名空間:

xmlns:openxu="https://schemas.android.com/apk/res-auto"

res-auto 表示自動查找。也可以寫成完整包名形式:xmlns:openxu="https://schemas.android.com/apk/com.example.openxu.myview"。

先在 res/values 下新建 attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyTextView">
        <!-- 引用系統已定義的 text 屬性 -->
        <attr name="android:text" />
        <attr name="mTextColor" format="color" />
        <attr name="mTextSize" format="dimension" />
    </declare-styleable>
</resources>

佈局文件中使用:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:openxu="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <com.example.openxu.myview.MyTextView
        android:layout_width="200dip"
        android:layout_height="100dip"
        android:background="#ff0000"
        android:text="我是文字"
        openxu:mtextcolor="#0000ff"
        openxu:mtextsize="25sp" />
</LinearLayout>

在構造方法中把屬性取出來:

public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);
    String text = ta.getString(R.styleable.MyTextView_android_text);
    int mTextColor = ta.getColor(R.styleable.MyTextView_mTextColor, Color.BLACK);
    int mTextSize = ta.getDimensionPixelSize(R.styleable.MyTextView_mTextSize, 100);
    Log.v("openxu", "text屬性值:" + text);
    Log.v("openxu", "mTextColor屬性值:" + mTextColor);
    Log.v("openxu", "mTextSize屬性值:" + mTextSize);
    ta.recycle();
}

五、AttributeSet 與 TypedArray 的分工

AttributeSet 顧名思義是屬性的集合,內部其實是一個 XML 解析器,會把佈局文件中該控件的所有屬性以鍵值對形式保存下來。只用它也完全可以拿到值:

public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    int count = attrs.getAttributeCount();
    for (int i = 0; i < count; i++) {
        String attrName = attrs.getAttributeName(i);
        String attrVal = attrs.getAttributeValue(i);
        Log.e("openxu", "attrName = " + attrName + " , attrVal = " + attrVal);
    }
}

輸出大致如下:

attrName = background , attrVal = @2131427347
attrName = layout_width , attrVal = 200.0dip
attrName = layout_height , attrVal = 100.0dip
attrName = text , attrVal = 我是文字
attrName = mTextSize , attrVal = 25sp
attrName = mTextColor , attrVal = #0000ff

問題顯而易見:AttributeSet 給出的是佈局文件裡原封不動的字符串。寬度是 200.0dip,要拿來用還得自己去掉單位再轉整型;background 寫的是資源引用,它直接丟給你一個帶 @ 的 ID,你還得自己動用 Resources 去換算真正的顏色。手工後處理的成本太高。

換成 TypedArray 就舒服多了:

public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);
    String mText = ta.getString(R.styleable.MyTextView_android_text);
    int mTextColor = ta.getColor(R.styleable.MyTextView_mTextColor, Color.BLACK);
    int mTextSize = ta.getDimensionPixelSize(R.styleable.MyTextView_mTextSize, 100);
    float width = ta.getDimension(R.styleable.MyTextView_android_layout_width, 0.0f);
    float height = ta.getDimension(R.styleable.MyTextView_android_layout_height, 0.0f);
    int background = ta.getColor(R.styleable.MyTextView_android_background, Color.BLACK);
    Log.v("openxu", "width:" + width);
    Log.v("openxu", "height:" + height);
    Log.v("openxu", "background:" + background);
    ta.recycle();
}

輸出直接就是可用的類型:

width:600.0
height:300.0
background:-12627531
mText:我是文字
mTextColor:-16777216
mTextSize:100

TypedArray 提供了一整套面向不同類型的取值方法(getString、getColor、getDimension、getDimensionPixelSize……),並支持傳入默認值,本質上是把 AttributeSet 之後的繁瑣轉換工作替我們做掉了。

六、declare-styleable 到底做了什麼

很多人好奇 declare-styleable 是否可有可無。答案是:寫與不寫都能編譯通過,但它會影響 R 文件的結構。

所有資源在 R 中都對應一個整型常量。屬性對應的是 R.attr 類;而一旦寫了 declare-styleable,R 中就會多出一個 R.styleable 內部類,它做的是「分組 + 記錄索引」:

public static final class styleable {
    public static final int[] MyTextView = {
            0x0101014f, 0x7f010038, 0x7f010039 };
    public static final int MyTextView_android_text = 0;
    public static final int MyTextView_mTextColor = 1;
    public static final int MyTextView_mTextSize = 2;
}

obtainStyledAttributes(attrs, R.styleable.MyTextView) 傳入的正是這個整型數組,TypedArray 依賴這組索引才能把屬性一一對應上。所以 declare-styleable 並非裝飾,而是 TypedArray 取值的必要基礎。

七、小結

為什麼要自定義屬性 → 如何定義並引用系統屬性 → format 的 11 種取值 → 構造方法中通過 TypedArray 取值 → AttributeSet、TypedArray 與 declare-styleable 的關係

把這五個環節串起來,自定義屬性這塊就再沒有黑盒了。

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