My Life with Android
Introduction Android Componets UserInterface Advanced UI Data Storage Advanced Concepts Others New Studio

Android String Resources

A string resource provides text strings for your application with optional text styling and formatting.

There are three types of resources that can provide your application with strings:
Type Description
String XML resource that provides a single string.
String Array XML resource that provides an array of strings.
Quantity Strings (Plurals) XML resource that carries different strings for pluralization.
All strings are capable of applying some styling markup and formatting arguments.

String

A string is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). So, you can combine string resources with other simple resources in the one XML file, under one <resources> element.
FILE LOCATION:
res/values/filename.xml

RESOURCE REFERENCE:
In Java: R.string.string_name
In XML: @string/string_name

SYNTAX:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="string_name">text_string</string>
</resources>

EXAMPLE:
XML file saved at res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
     <string name="app_name">WhatsApp</string>
</resources>
This layout XML applies a string to a View:
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/app_name" />

This application code retrieves a string:
String string = getString(R.string.hello); You can use either getString(int) or getText(int) to retrieve a string. getText(int) will retain any rich text styling applied to the string.

Escaping apostrophes and quotes

If you have an apostrophe (') in your string, you must either escape it with a backslash (\') or enclose the string in double-quotes ("").
Examples :
<string name="good_example">This\'ll work</string>
<string name="good_example_2">"This'll also work"</string>
If you have a double-quote in your string, you must escape it (\")
<string name="good_example">This is a \"good string\".</string>

Formatting strings

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource.
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);