Android: Adding and referencing an XML resource


Adding an XML resource

Inside your res folder is a values folder you can right-click on this and create a New > Values resource file. Inside this, for the purpose of creating a simple list of strings, we can simply place tags and strings in an identical way to that in which we find in the strings.xml file:
<resources><string name="app_name">DraggingView</string></resources>
If we want to create an array however, whether that be an integer or string array we must first identify the array as such by additional level of nesting:
<resources>
    <string-array name="font_sizes">
        <item value="10">"10"</item>
        <item value="15">"15"</item>
        <item value="20">"20"</item>
    </string-array>
</resources>

Referencing the XML resource

To then reference that resource within your java code, we can write simply:
R.array.font_sizes
For a string you would write:
R.string.app_name
No notice is taken of the filename when references are made only of the type contained within them. While the resources can be in separate files, they are treated as if all values are contained in one single file, hence no need to identify filenames.

When this will be useful

This will prove useful, where for example you might want to create an array adapter for a spinner (more on this in the next Android post).
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.font_sizes, android.R.layout.simple_spinner_dropdown_item);
Or simply retrieve a string array:
String[] myStringArray = getResources().getStringArray(R.array.font_sizes);

Where next?

Sticking with the theme of XML, I'll be looking at toolbars and their menu items next time (not only the designated action bar but also secondary toolbars).

Comments