支持不同的语言
从代码中提取 UI 字符串并保存到外部文件总是一个好的习惯。在每个 Android 工程中,Android利用 Resources目录使之变得很容易。
如果你使用 Android SDK Tools (阅读 Creating an Android Project),此工具会在 Android 工程顶级目录创建一个 res/ 目录。在 res/ 目录中存放的是各种资源类型。也有一些例如 res/values/strings.xml 的默认文件,里面存放的是字符串值。
创建本地目录和字符串文件
为了添加支持更多的语言,在 res/ 目录下创建额外的在目录名后包含一个连字符和 ISO 语言码的 values 目录。例如,values-es/ 是一个本地语言码为 “es” 包含简单资源的目录。安卓通过设备运行时的本地设置来正确加载相关匹配资源,更多信息,查看 Providing Alternative Resources 。
一旦你想在设备上支持一些语言,创建资源子目录和字符串资源文件。例如:
MyProject/ res/ values/ strings.xml values-es/ strings.xml 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>
在运行时,安卓系统会根据用户设备的当前设置使用适当的字符串资源。
例如,下面是一些不同语言对应的不同字符串资源。
英语 (默认),/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 文件中使用用 <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> 语法引用一个字符串资源, 不论何时,这个 XML属性能够接受一个字符串值。
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" />