Android 利用 res value xml 建立 key-value 資料

key-value data

在 Android 中可以在 res 目錄下建立 key-value xml 資料,在程式中使用。

建立陣列

有時候會需要一組 key-value 的固定資料,但不想寫死在程式碼中,而想利用資源中的 xml 來建立,不只容易修改,在做多國語言時也可以方便使用。

在 res/values 目錄中建立一個 xml 資源檔,同時建立兩個互相對映的字串及數值陣列,如下:
<?xml version="1.0" encoding="utf-8"?>
<resources> <string-array name="area_key"> <item>台北</item> <item>台中</item> <item>台南</item> <item>高雄</item> <item>宜蘭</item> <item>花蓮</item> </string-array> <integer-array name="area_value"> <item>0</item> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> </integer-array> </resources>

程式碼(*.java)

String[] areaKey = getResources().getStringArray(R.array.area_key);
int[] areaValue = getResources().getIntArray(R.array.area_value);

HashMap<String, Integer> areas = new HashMap<String, Integer>();

for (int i = 0; i < areaKey.length; i++) {
  areas.put(areaKey[i], areaValue[i]);
}
這樣就把資源中 xml 的資料以 Map 的型態建立,之後就可以在程式碼中來利用。
本文網址:http://blog.tonycube.com/2011/08/res-valuexmlkey-value.html
Tony Blog 撰寫,請勿全文複製,轉載時請註明出處及連結,謝謝 😀

我要留言

留言小提醒:
1.回覆時間通常在晚上,如果太忙可能要等幾天。
2.請先瀏覽一下其他人的留言,也許有人問過同樣的問題。
3.程式碼請先將它編碼後再貼上。(線上編碼:http://bit.ly/1DL6yog)
4.文字請加上標點符號及斷行,難以閱讀者恕難回覆。
5.感謝您的留言,您的問題也可能幫助到其他有相同問題的人。