編輯:關於 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 一共支持 11 種取值。
<attr name="background" format="reference" />
使用:<ImageView android:background="@drawable/pic" />
使用:<TextView android:textColor="#00FF00" />
使用:<Button android:focusable="true" />
使用:<Button android:layout_width="42dip" />
使用:<attr name="layout_weight" format="float" />
使用:<TextView android:text="我是文本" />
使用:<Rotate android:pivotX="200%" />
<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"。
<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 可以多值組合。
允許一個屬性同時接受多種類型,最典型的就是 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 顧名思義是屬性的集合,內部其實是一個 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 是否可有可無。答案是:寫與不寫都能編譯通過,但它會影響 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 的關係
把這五個環節串起來,自定義屬性這塊就再沒有黑盒了。
Realm 行動資料庫入門:跨平台 ORM、效能優勢與學習重點
Realm 是什麼Realm 是一套跨平台行動資料庫引擎,支援 iOS、OS X 與 Android。它並非建立在 SQLite 之上的 ORM,而是使用自有核心引擎,目
Android 仿外賣購物車實作全解:懸停標題、左右聯動與拋物線動畫
效果預覽 先盤點技術點 畫面看起來熱鬧,但真正需要花心思的其實就這幾塊: - 清單標題懸停 - 左右兩欄滑動聯動 - 加入商品時的拋物線動畫 - 底部彈出購物車清單
深入 Android 五大佈局物件: from FrameLayout 到 TableLayout
佈局是 Android UI 開發的骨架。Android 提供了五種基礎佈局——FrameLayout(框架佈局)、LinearLayout(線性佈局)、Absolute
Android 開發筆記:廣播接收器 BroadcastReceiver 完全指南
一、廣播接收器是什麼 BroadcastReceiver 是 Android 四大組件之一,可以把它理解成一個掛在系統層級上的「全局監聽器」。它本身不開界面、不長駐進程,