Home > Android > Android Global Strings

Android Global Strings

A global string, or array of strings are declared in an external xml file in the resource folder:<project>/res/values/strings.xml

Declaring a global string

&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
   &lt;string name="hello">Hello World!
   &lt;string name="app_name">MyTest
&lt;/resources>

Using a global string while creating a TextView

XML example:

&lt;TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   />

Code example:

((TextView)findViewById(R.id.MyTextView)).setText(R.string.hello);

Getting a global string

String hello = context.getString(R.string.hello);

Global String Array

Declaration in a Global String Array

&lt;?xml version="1.0" encoding="utf-8"?>
&lt;esources>
   &lt;string-array name="planets_array">
       &lt;item>Mercury&lt;/item>
       &lt;item>Venus&lt;/item>
       &lt;item>Earth&lt;/item>
       &lt;item>Mars&lt;/item>
   &lt;/string-array>
&lt;/resources>

Code usage

String[] planets =
    context.getResources().getStringArray(R.array.planets_array);