Strings are typically stored in the resource file
strings.xml. They are defined using a
<string> XML element.
The purpose of strings.xml is to allow internationalisation. You can define a strings.xml for each language iso code. Thus when the system looks for the string ‘app_name’ it first checks the xml file corresponding to the current language, and if it is not found, looks for the entry in the default strings.xml file. This means you can choose to only localise some of your strings while not others.
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Hello World App</string> <string name="hello_world">Hello World!</string> </resources>
Once a string is defined in an XML resource file, it can be used by other parts of the app.
An app’s XML project files can use a
<string> element by referring to
@string/string_name. For example, an app’s manifest (/manifests/AndroidManifest.xml) file includes the following line by default in Android Studio:
This tells android to look for a
<string> resource called “app_name” to use as the name for the app when it is installed or displayed in a launcher.
Another time you would use a
<string> resource from an XML file in android would be in a layout file. For example, the following represents a TextView which displays the
hello_world string we defined earlier:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world"/>
You can also access
<string> resources from the java portion of your app. To recall our same
hello_world string from above within an Activity class, use:
String helloWorld = getString(R.string.hello_world);