Android has a very nice mechanisim to switch the strings according to the locale.
All the developer has to do is keep translated version of strings.xml in different folders as per the locale guidelines and the android firmware will take care of the same.
Storing the values of a single dimension array is very straight forward , however it is slightly tricky when it comes to double dimension array.
Create a resource file in res/values folder called arrays.xml.
Inside it create a couple of arrays like so
<string-array name="friday"> <item>@string/friday_one</item> <item>@string/friday_two</item> <item>@string/friday_three</item> </string-array> <string-array name="monday"> <item>@string/mon_one</item> <item>@string/mon_two</item> <item>@string/mon_three</item> </string-array>
In the above the items are present in the string.xml file.
Now create an array of arrays in the same file like so
<array name="words"> <item>@array/friday</item> <item>@array/monday</item> </array>
Each item above refers to an array , while those arrays in turn refers to items from the string.xml
Now lets have a look at the strings.xml file.
<string name="friday_one">Friday Night fever</string> <string name="friday_two">TGIF</string> <string name="friday_three">I am dog tired</string> <string name="mon_one">I hate monday</string> <string name="mon_two">Hell starts</string> <string name="mon_three">Quit Monday</string>
Well as expected the values of the items referred to by the array.
Now lets have a look at the the code to access the same from the code .
Resources res = getResources(); TypedArray ta = res.obtainTypedArray(R.array.words); Map<String, List<String>> wordMap = new HashMap<String, List<String>>(); int n = ta.length(); for (int i = 0; i < n; ++i) { //String key = ta.get; int resId = ta.getResourceId(i, 0); String key = res.getResourceEntryName(resId); List<String> values = Arrays.asList(res.getStringArray(resId)); wordMap.put(key, values); } ta.recycle(); for (String key : wordMap.keySet()) { Log.e(" Test ","Key is "+key); for ( String value : wordMap.get(key)) Log.e(" Test ","Vlaue is "+value); }
The code is simple really , first reading the typed array words from the resources arrays.xml
This contains the two arrays “friday” and “monday”.
Now the trick is to get the resource ids for those arrays and then return them as one dimensional array , I am then storing them as a map with the key as the array name.
It is important to do ta.recycle() to release the reosurces .
Printing the values will give the output
Test ( 339): Key is friday E/ Test ( 339): Vlaue is Friday Night fever E/ Test ( 339): Vlaue is TGIF E/ Test ( 339): Vlaue is I am dog tired E/ Test ( 339): Key is monday E/ Test ( 339): Vlaue is I hate monday E/ Test ( 339): Vlaue is Hell starts E/ Test ( 339): Vlaue is Quit Monday
You can download the project for reference.