It is a good habit to extract strings from the code into an external file. Android provides a dedicated resource folder for each project.
If you use the SDK tool to create a project, this tool creates a res/folder in the root directory of the project. The subfolders in this folder indicate different resource types. Some default files, such as res/values/strings. xml, define the value of your string.
Create a region folder and a string File
To support multiple languages, add values to/res and a folder named by the ISO country code. For example, values-es/contains resources for countries where the language code is 'els. Android loads the appropriate resources based on the language settings in the localization settings of the device.
Once you decide to support a specific language, create the corresponding sub-directories and string files, for example:
MyProject/
Res/
Values/
Strings. xml
Values-es/
Strings. xml
Values-fr/
Strings. xml
Add the string value to an appropriate file.
When running, the android system uses the corresponding string resources according to the current region set in the User device.
For example, below are some different string resources that correspond to different languages.
English (default region),/values/strings. xml:
[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<Resources>
<String name = "title"> My Application </string>
<String name = "hello_world"> Hello World! </String>
</Resources>
Spanish,/values-es/strings. xml:
[Html
<? Xml version = "1.0" encoding = "UTF-8"?>
<Resources>
<String name = "title"> Mi Aplicaci ón </string>
<String name = "hello_world"> Hola Mundo! </String>
</Resources>
French,/values-fr/strings. xml:
[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<Resources>
<String name = "title"> Mon Application </string>
<String name = "hello_world"> Bonjour le monde! </String>
</Resources>
Tip: You can use regional delimiters for any resource type. For example, you can provide different images for different regions. For more information, see Localization.
Use string Resources
You can reference these resources in the source code and other XML files by using the resource name, which is defined by the name attribute of the <string> element.
In the code, you can refer to syntax calls like R. string. <string_name>. The following function calls a string resource using this method.
For example:
[Java]
// Obtain the string from the program resource
String hello = getResources (). getString (R. string. hello_world );
// Provide string resources for the method that requires a string
TextView textView = new TextView (this );
TextView. setText (R. string. hello_world );
In an XML file, you can use the syntax @ string/<string_name> to receive a string resource. For example:
[Html] www.2cto.com
<TextView
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "@ string/hello_world"/>
Author: lixiang0522