## 類型化數組
在 XML 中定義的`[TypedArray](https://developer.android.google.cn/reference/android/content/res/TypedArray)`。您可以使用這種資源創建其他資源(例如可繪制對象)的數組。請注意,此類數組不要求所含的資源具有相同的類型,因此您可以創建混合資源類型的數組,但必須知道數組中有哪些數據類型及其位置,以便可以使用`[TypedArray](https://developer.android.google.cn/reference/android/content/res/TypedArray)`的`get...()`方法正確獲取每一項數據。
**注意**:類型化數組是使用`name`屬性中提供的值(而不是 XML 文件的名稱)引用的簡單資源。因此,您可以在一個 XML 文件中將類型化數組資源與其他簡單資源合并到一個`<resources>`元素下。
### 文件位置:
`res/values/*filename*.xml`
該文件名可以任意設置。`<array>`元素的`name`將用作資源 ID。
編譯后的資源數據類型:
指向`[TypedArray](https://developer.android.google.cn/reference/android/content/res/TypedArray)`的資源指針。
### 資源引用:
在 Java 中:`R.array.*array_name*`
在 XML 中:`@[*package*:]array.*array_name*`
### 語法:
~~~
? ? <?xml version="1.0" encoding="utf-8"?>
? ? <resources>
? ? ? ? <array
? ? ? ? ? ? name="integer_array_name">
? ? ? ? ? ? <item>resource</item>
? ? ? ? </array>
? ? </resources>
~~~
### 元素:
* `<resources>`
**必需**。該元素必須是根節點。
沒有屬性。
* `<array>`
定義一個數組。包含一個或多個`<item>`子元素。
屬性:
* `android:name`
字符串。數組的名稱。此名稱將用作引用數組的資源 ID。
* `<item>`
通用資源。該值可以是對資源或簡單數據類型的引用。必須是`<array>`元素的子元素。
沒有屬性。
### 示例:
保存在`res/values/arrays.xml`的 XML 文件:
~~~
? ? <?xml version="1.0" encoding="utf-8"?>
? ? <resources>
? ? ? ? <array name="icons">
? ? ? ? ? ? <item>@drawable/home</item>
? ? ? ? ? ? <item>@drawable/settings</item>
? ? ? ? ? ? <item>@drawable/logout</item>
? ? ? ? </array>
? ? ? ? <array name="colors">
? ? ? ? ? ? <item>#FFFF0000</item>
? ? ? ? ? ? <item>#FF00FF00</item>
? ? ? ? ? ? <item>#FF0000FF</item>
? ? ? ? </array>
? ? </resources>
~~~
以下應用代碼會檢索每個數組,然后獲取每個數組中的第一個條目:
~~~
? ? Resources res = getResources();
? ? TypedArray icons = res.obtainTypedArray(R.array.icons);
? ? Drawable drawable = icons.getDrawable(0);
? ? TypedArray colors = res.obtainTypedArray(R.array.colors);
? ? int color = colors.getColor(0,0);
~~~