2015-10-19 34 views
0

基本上我試圖實現的是從代碼訪問兩個相關的資源。在XML中關聯不同數據的最簡單和最有效的方式是什麼?

考慮這個例子,我能想到的我的問題的最佳解決方案:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string name="black">⬛</string><color name="black_c">#000000</color> 
    <string name="white">⬜</string><color name="white_c">#ffffff</color> 
</resources> 

給出一個字符串n在我的代碼可以訪問與之相關聯的兩個第二個字符串(⬛或⬜)或通過在N字符串的末尾添加「_c」來增加顏色。

所以,如果N = 「黑」 我可以使用n同時檢索和⬛#000000(有N + 「_c」)

有沒有更好的方式來做到這一點?我的解決方案感覺有點怪異。希望我能夠解釋我想達到的目標,謝謝!

回答

1

我有另一個建議。我希望它能幫助你。

如果你有colors.xml和strings.xml中的值(目錄內)

<!-- colors.xml --> 
<resources> 
    <color name="black">#000000</color > 
</resources> 

<!-- strings.xml --> 
<resources> 
    <string name="black">Some black string</string> 
</resources> 

使用相同的名稱,如果你能得到不同的ID,您可以訪問他們兩個(即R.string.black或R.color.black)。 ()`方法可以做到這一點。所以你可以試試(未經測試)

String name = "black; 
String choice = "color"; //or "string" dependending on if you want the color or the string 
int resID = getResources().getIdentifier(name, choice, getPackageName()); 
Resources resources = getResources(); 

//Then access using 
//If choice=="color" 
int color = resources.getColor(resId); 

//If choice=="string" 
String text = resources.getString(resId); 
+0

謝謝!沒有想過這個,它比我的解決方案更好。我在你的答案中更正了一個xml文件名。 – Bonfi

+0

不客氣;) – ThomasThiebaud

0

雅這聽起來有點哈克。您可以使用樣式將所有資源(作爲該樣式的屬性)進行分組,然後閱讀這些樣式。更多的信息在這裏:How to retrieve style attributes programmatically from styles.xml

但這再次聽起來很亂。你的實際需求是什麼?你建議的方式聽起來不錯。從性能角度來看,您可以繼續執行該實現,但不會有任何額外的考慮。只要確保你編寫了一個簡潔的API來從你的xml中獲取數據。

相關問題