`

Android Training - 支持不同的语言

阅读更多
把UI中的字符串从代码中提取到一个外部文件中是一个好的习惯。Android为每个项目提供一个专门的资源文件夹来实现。

如果你使用SDK工具来创建的项目,那么这个工具会在项目的根目录创建一个res/文件夹,这个文件夹中的子文件夹表示不同的资源类型。这里也有一些默认的文件,比如res/values/strings.xml,它定义了你的字符串的值。

创建区域文件夹和字符串文件

为了支持多国语言,你需要在/res中添加values加一个连字符号和一个ISO国家代码命名的文件夹。比如,values-es/包含了的资源是为语言代码为'es'的国家提供的。android根据设备中本地化设置中的语言设置对应的加载适合的资源。

一旦你决定支持某个语言,那么创建相应的子目录和字符串文件,例如:
MyProject/    res/       values/           strings.xml       values-es/           strings.xml       values-fr/           strings.xml
在适当的文件中添加字符串的值。

在运行的时候,android系统根据用户设备中设置的当前区域使用对应的字符串资源。

例如,下面是一些不同的字符串资源,对应不同的语言。

英语(默认区域),/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>

西班牙语,/values-es/strings.xml:
<?xml version="1.0" encoding="utf-8"?><resources>    <string name="title">Mi Aplicación</string>    <string name="hello_world">Hola Mundo!</string></resources>

法语,/values-fr/strings.xml:
<?xml version="1.0" encoding="utf-8"?><resources>    <string name="title">Mon Application</string>    <string name="hello_world">Bonjour le monde !</string></resources>

提示:可以在任何资源类型上使用区域限定符,比如你可以为不同的区域提供不同的图片,想了解更多,请看 Localization .

使用字符串资源

你可以在源代码和其他XML文件中通过资源名称引用这些资源,这个名称是通过<string>元素的name属性定义的。

在代码中,你可以参考类似R.string.<string_name>这样的语法调用,下面的函数中就是通过这个方法去调用一个字符串资源的。

例如:
// 从程序资源中获取字符串String hello = getResources().getString(R.string.hello_world);// 为需要字符串的方法提供字符串资源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" />


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics