2015-12-24 16 views
10

ho array di stringhe che assomiglia a questo:Ricevi un nome attributo dalla stringa di matrice

<string-array name="USA"> 
    <item name="NY">001</item> 
    <item name="LA">002</item> 
    <item name="WA">003</item> 
</string-array> 

posso ottenere quei numeri da:

Resources res = getResources(); 
int arryid = res.getIdentifier("USA", "array", getPackageName()); 
String[] numbers = res.getStringArray(arryid); 

Ma come posso anche ottenere i nomi (NY, LA, WA)? Nota che ho molte contee ... Forse usi un approccio diverso?

+0

È possibile invece creare HashMap. Controlla [questo] (http://stackoverflow.com/a/13032780/3022836) – Kunu

+0

Prova questo. http://stackoverflow.com/questions/7256514/search-value-for-key-in-string-array-android –

risposta

6

In official document non c'è name attributo per <item>. Quindi non penso che ci sarà un modo per ottenere quelle chiavi.

Tuttavia, se si desidera ottenere il nome di string o string-array, è possibile farlo a livello di programmazione ma non per lo <item>.

1
String[] numbers = getResources().getStringArray(R.array.USA); 

per ottenere i dati dall'uso matrice.

numbers[id] 

aggiungere array come questo.

4

Come "001" è solo l'indice, perché non utilizzarlo semplicemente?

<string-array name="USA"> 
    <item>NY</item> 
    <item>LA</item> 
</string-array> 

Poi basta utilizzare index + 1 per la posizione:

String[] usaStates = getResources().getStringArray(R.array.USA); 

int index = 0; 

String firstStateName = usaStates[index]; 
int firstStatePosition = (index + 1); 

A parte questo, è possibile utilizzare due array e unirle in una HashMap:

<string-array name="USA"> 
    <item>NY</item> 
    <item>LA</item> 
</string-array> 

<string-array name="USA_pos"> 
    <item>001</item> 
    <item>002</item> 
</string-array> 

String[] usaStates = getResources().getStringArray(R.array.USA); 
String[] usaStatePositions = getResources().getStringArray(R.array.USA_pos); 

Map <String, String> map = new HashMap<>(usaStates.length); 

for (int i = 0; i < usaStates.length; i++) { 
    map.put(usaStates[i], usaStatePositions[i]); 
} 
Problemi correlati