編輯:關於 Android 開發
Android 內建的各種 Widget 都提供了大量 XML 屬性,讓我們能在 layout 檔中直接為控制項賦值:
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Hello World!" />
透過 TextView 提供的 android:text,就能設定它的文字內容。那麼,當我們自己寫一個自定義 View 時,也想讓它能用同樣的方式在 XML 中設定屬性,該怎麼做?
假設我們有一個自定義 View,類名是 com.ispring.attr.MyView。整體流程可以拆成三步:
① 在 XML 資源檔中定義 attr,並指定資料型別;
② 在自定義 View 的建構式中解析這些屬性值,存入對應的成員變數;
③ 在 layout 檔中為自定義 View 的 XML 屬性賦值。
先在 res/values 下新增一個名為 attrs_my_views.xml 的檔案(檔名不重要,只要是 XML 檔即可)。根節點是 <resources>,在其下可以放多個 <attr> 節點,透過 name 指定屬性名稱,透過 format 指定值的型別:

format 支援的型別有:enum、boolean、color、dimension、flag、float、fraction、integer、reference、string。
enum 讓屬性值只能從列舉项中挑選:
<attr name="customAttr">
<enum name="man" value="0" />
<enum name="woman" value="1" />
</attr>
這樣 customAttr 就只接受 man 或 woman 了。
flag 則是位元標記。它與 enum 相似,但允許用 | 組合成多個值,每個值對應一個 bit 位:
<attr name="customAttr">
<flag name="none" value="0" />
<flag name="bold" value="0x1" />
<flag name="italic" value="0x2" />
<flag name="underline" value="0x4" />
</attr>
值一般取 0 或 2 的 N 次方。使用時既能設單值,也能組合,例如 app:customAttr="italic|underline"。要注意的是:使用 flag 時不要在 attr 上設定 format="flag",直接在節點下放 flag 子節點即可。

要使用自定義屬性,必須先宣告一個自定義命名空間以區別於 xmlns:android。命名空間的名稱可以任意取,慣例是用 xmlns:app:
<com.ispring.attr.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:customText="Hello World!"
app:customColor="#FF0000FF" />
我們讓 MyView 繼承 View,並希望能顯示一段指定顏色的文字,等同於一個極簡版的 TextView。資源檔如下:
<resources>
<attr name="customText" format="string" />
<attr name="customColor" format="color" />
</resources>
編譯專案後會產生 R.java。Android Studio 專案中它的位置是 app\build\generated\source\r\debug\com\ispring\attr\R.java,其中會出現內部類別 public static final class attr,裡面可以找到 customText 與 customColor:

R.attr.customText 與 R.attr.customColor 分別就是這兩個屬性的資源 ID。
MyView 的實作如下:
package com.ispring.attr;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View {
// 存放要顯示的文字
private String mCustomText;
// 存放文字的顯示顏色
private int mCustomColor = 0xFF000000;
// 畫筆
private TextPaint mTextPaint;
// 字級大小
private float fontSize = getResources().getDimension(R.dimen.fontSize);
public MyView(Context context) {
super(context);
init(null, 0);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
if (attrs != null) {
// 取得 XML 屬性的數量
int count = attrs.getAttributeCount();
// 依索引遍歷所有屬性
for (int i = 0; i < count; i++) {
int attrResId = attrs.getAttributeNameResource(i);
switch (attrResId) {
case R.attr.customText:
mCustomText = attrs.getAttributeValue(i);
break;
case R.attr.customColor:
// 讀不到時預設為黑色
mCustomColor = attrs.getAttributeIntValue(i, 0xFF000000);
break;
}
}
}
mTextPaint = new TextPaint();
mTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextSize(fontSize);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mCustomText != null && !mCustomText.equals("")) {
mTextPaint.setColor(mCustomColor);
canvas.drawText(mCustomText, 0, fontSize, mTextPaint);
}
}
}
重點都在 init 方法裡。傳入的 AttributeSet 可以視為一個索引陣列,裡頭存著屬性的索引,透過索引就能取到屬性名與屬性值。幾個常用的方法:
getAttributeCount() 取得屬性數量;getAttributeNameResource(int index) 取得該屬性在 R.attr 中的資源 ID;getAttributeValue(int index) 取得字串值;getAttributeIntValue / getAttributeFloatValue 等則回傳其他型別。
由於 Android 用一個 4 位元組的 int 表示顏色,所以 customColor 用 getAttributeIntValue 讀取。最後在 onDraw 中設定畫筆顏色並繪製文字。
運行效果如下,畫面上出現藍色的「Hello World!」,代表自定義屬性生效了:

上面把 attr 直接定義在 <resources> 底下,這樣做有一個明顯的限制:無法透過 style 或 theme 來設定這些屬性的值。
要支援 style,就得把 attr 包進 <declare-styleable> 節點裡:
<resources>
<declare-styleable name="MyView">
<attr name="customText" format="string" />
<attr name="customColor" format="color" />
</declare-styleable>
</resources>
name 一般設為自定義 View 的類名,這裡是 MyView。
兩種定義方式在 R.attr 中的結果是一樣的,都會產生 R.attr.customText 與 R.attr.customColor。差別在於 declare-styleable 會額外在 R.styleable 中產生一組常量:

R.styleable.MyView 是一個 int 陣列,內容為 [R.attr.customText, R.attr.customColor];同時還會產生 R.styleable.MyView_customText 與 R.styleable.MyView_customColor,命名規則是「styleable 名稱 + 下劃線 + attr 名稱」。

在 declare-styleable 中定義的屬性,要透過 theme 的 obtainStyledAttributes 來讀取。它有三個重載版本:
public TypedArray obtainStyledAttributes(int[] attrs) public TypedArray obtainStyledAttributes(int resid, int[] attrs) public TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
先來看最完整的第三個版本:
private void init(AttributeSet attributeSet, int defStyle) {
if (attributeSet != null) {
// 取得目前 MyView 所在 Activity 的 theme
Resources.Theme theme = getContext().getTheme();
TypedArray typedArray = theme.obtainStyledAttributes(
attributeSet, R.styleable.MyView, 0, 0);
int count = typedArray.getIndexCount();
for (int i = 0; i < count; i++) {
int styledAttr = typedArray.getIndex(i);
switch (styledAttr) {
case R.styleable.MyView_customText:
mCustomText = typedArray.getString(i);
break;
case R.styleable.MyView_customColor:
mCustomColor = typedArray.getColor(i, 0xFF000000);
break;
}
}
// 用完記得回收
typedArray.recycle();
}
// ...其餘初始化程式碼
}
第二個參數傳入 R.styleable.MyView,也就是告訴系統「我想取 customText 與 customColor 這兩個屬性」。
接著在 styles.xml 中定義一個 style:
<style name="RedStyle">
<item name="customText">customText in RedStyle</item>
<!-- 紅色 -->
<item name="customColor">#FFFF0000</item>
</style>
並在 layout 中套用:
<com.ispring.attr.MyView
android:layout_height="match_parent"
android:layout_width="match_parent"
style="@style/RedStyle"
app:customText="customText in AttributeSet" />
執行結果:

雖然我們沒有直接設 customColor,但 style 中的紅色生效了;而 customText 則採用了 layout 中直接設定的值。由此可以得出第一條結論:style 是 layout 屬性的候補值,AttributeSet 的優先級高於 style。
第三個參數 defStyleAttr 指向某個 style 屬性的 ID。當 AttributeSet 與 style 屬性都找不到值時,系統會去目前 theme 中查詢這個屬性,若其值是一個 style 資源,就再進去那個 style 裡找。
先在 attrs 檔中宣告這個屬性(format 為 reference):
<resources>
<attr name="myViewStyle" format="reference" />
</resources>
並在 AppTheme 中把它指向 GreenStyle:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="myViewStyle">@style/GreenStyle</item>
</style>
<style name="GreenStyle">
<item name="customText">customText in GreenStyle</item>
<item name="customColor">#FF00FF00</item>
</style>
<style name="HelloWorldStyle">
<item name="customText">Hello World!</item>
</style>
MyView 中的呼叫改為:
TypedArray typedArray = theme.obtainStyledAttributes(
attributeSet, R.styleable.MyView, R.attr.myViewStyle, 0);
layout 中只設 style,不直接設屬性:
<com.ispring.attr.MyView
android:layout_height="match_parent"
android:layout_width="match_parent"
style="@style/HelloWorldStyle" />
執行結果是綠色的「Hello World!」:

原因是這樣的:layout 沒設屬性,所以 AttributeSet 這關撲空;接著看 style(HelloWorldStyle),它定義了 customText 為「Hello World!」,但沒有定義 customColor;於是系統轉而查 theme 中 myViewStyle 的值,也就是 GreenStyle,並在其中找到綠色的 customColor 作為候補。
所以 defStyleAttr 的作用是:當前兩關都取不到值時,透過 theme 的某個屬性間接找到一個 style 資源,再從中取值。
第四個參數 defStyleRes 與 defStyleAttr 類似,都是候補值且優先級最低。差別是:defStyleAttr 需要繞一圈透過 theme 屬性才能找到 style,而 defStyleRes 本身就直接是一個 style 資源。
新增 BlueStyle:
<style name="BlueStyle">
<item name="customText">customText in BlueStyle</item>
<item name="customColor">#FF0000FF</item>
</style>
呼叫時把第四個參數填上去:
TypedArray typedArray = theme.obtainStyledAttributes(
attributeSet, R.styleable.MyView, 0, R.style.BlueStyle);

有個細節值得注意:只有在 defStyleAttr 為 0、或該屬性在 theme 中找不到時,才會使用 defStyleRes。 如果 defStyleAttr 不為 0 且能找到,但它對應的 style 完全沒有定義任何 XML 屬性值,那麼 defStyleRes 也不會被採用。
雖然不透過 <declare-styleable> 也能定義屬性,但仍強烈建議放在裡面,因為系統會幫我們在 R.styleable 中產生可直接使用的常量,避免手寫字串帶來的錯誤。
最後記住這條優先級鏈,由高低排序:
layout 中直接設定的屬性值(AttributeSet) > View 的 style 屬性 > defStyleAttr > defStyleRes
ListView 入門實戰:從基礎列表到自定義圖文列表
ListView 入門實戰:從基礎列表到自定義圖文列表 在 Android 開發裡,ListView 幾乎是最常被使用到的列表控件之一。它看起來簡單,但想要用得得心應手,
讀取手機通訊錄並用 PinnedSectionListView 分組展示、點擊撥號
要做一個類似系統通訊錄的頁面,需要解決三件事:讀取聯絡人資料、依姓名首字母分組並讓組標題懸浮固定、點擊項目直接撥號。以下用 PinnedSectionListView 一
ListView 原理與優化:getView、convertView 與 ViewHolder 的完整理解
ListView 為什麼需要優化 ListView 是 Android 中常見的列表元件,但當列表項目變多、項目配置變複雜,或每個項目都需要載入圖片時,若沒有理解它的繪製
ActionBar 結構圖解與功能一覽
一、四大組成部分 ActionBar 是應用頂部的操作列,由四個部分構成: App icon:應用圖標,左側可帶返回箭頭,兼具品牌識別與導航職能。 View Cont