支持不同的语言
将APP代码中的UI字符串提取到一个外部的文件中是一个很好的惯例。Android工程下的资源目录能轻易实现这个功能。
如果你使用Android SDK工具创建了你的工程,这个工具会在工程的顶层创建一个res/目录。这个目录里面是不同类型资源的子目录。有些是默认的文件,例如res/values/strings.xml .里面存放的是字符串的值。
创建现场目录和字符串文件
要支持更多的语言,需要在res/目录下创建额外的values目录,命名规则是:values + 连接符+ISO 国家代码。例如:values-es.Android会根据运行时环境来加载合适的资源。
一旦你决定要支持某种语言,需要创建资源子目录和string资源文件,例如:
MyProject/
res/
values/
strings.xml
values-es/
strings.xml
values-fr/
strings.xml
为每个场景添加字符串值到合适的文件中去。
运行时,系统会根据用户设备的当前场景设置来选择合适的字符串资源。
例如,如下是不同国家的不同字符串文件。
英语是默认的场景,/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title">My Application</string>
<string name="hello_world">Hello World!</string>
</resources>
西班牙,/res/values-es/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<stringname="title">Mi Aplicación</string>
<stringname="hello_world">Hola Mundo!</string>
</resources>
法语, /values-fr/strings.xml
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<stringname="title">Ma Application</string>
<stringname="hello_world">Bonjour tout le Monde!</string>
</resources>
注意:在任何资源类型中,你都能使用场景限定。例如不同的场景使用不同的图片,详见Localization.
使用字符串资源
通过资源名字,你就可以在代码中或者其它XML文件中引用字符串资源。资源名是<string>元素的name属性定义的。
在源代码里面,你能通过R.string.<string_name>来引用字符串资源。例子:
// Get a string resource from your app's Resources
String hello = getResources().getString(R.string.hello_world);
// Or supply a string resource to a method that requires a string
TextView textView = new TextView(this);
textView.setText(R.string.hello_world);
在其它XML文件中,你能够通过:@string/<string_name>来引用字符串资源。例子:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"/>