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

在 XML 中定義 drawable/id 陣列,並在程式碼裡讀出來

編輯:關於 Android 程式設計

如果你需要在程式碼中為一群 View 設定對應的一批圖片資源——例如幫 ListView 或 GridView 的每個 item 配一張圖——最乾淨的做法是在 XML 裡宣告一個資源陣列,再用程式碼讀取,而不是把資源 ID 硬寫在 Java 裡。

踩過的坑

一開始我直覺地寫成 integer-array:

<integer-array name="actions_images">
    <item>@drawable/pencil1</item>
    <item>@drawable/pencil2</item>
    <item>@drawable/pencil3</item>
    <item>@drawable/pencil4</item>
    <item>@drawable/pencil5</item>
    <item>@drawable/pencil6</item>
</integer-array>

然後想用 getResources().getIntArray() 把圖片 ID 取出來——結果完全行不通。查了 Stack Overflow 才找到正解。

正確寫法

1. XML 中改用 string-array:

<string-array name="actions_images">
    <item>@drawable/pencil1</item>
    <item>@drawable/pencil2</item>
    <item>@drawable/pencil3</item>
    <item>@drawable/pencil4</item>
    <item>@drawable/pencil5</item>
    <item>@drawable/pencil6</item>
</string-array>

2. Java 中用 TypedArray 讀取:

TypedArray ar = context.getResources().obtainTypedArray(R.array.actions_images);
int len = ar.length();
int[] resIds = new int[len];
for (int i = 0; i < len; i++)
    resIds[i] = ar.getResourceId(i, 0);
ar.recycle();

跑完這段,所有圖片 ID 就都存在 resIds 裡了,之後要設定時直接 img.setImageResource(resIds[0]) 即可。

想在 XML 中定義 id 陣列,做法完全相同:一樣宣告成 string-array,一樣用 obtainTypedArray() 搭配 getResourceId() 取出。

順帶一提,ar.recycle() 別忘了呼叫。TypedArray 會佔用一點原生記憶體,用完不歸還,在列表大量重複呼叫的場景下容易累積出不必要的開銷。

參考來源:Stack Overflow: Android - Storing R.drawable IDs in XML array

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