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:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="title">My Application</string>  
  4.     <string name="hello_world">Hello World!</string>  
  5. </resources>  

西班牙语,/values-es/strings.xml:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="title">Mi Aplicación</string>  
  4.     <string name="hello_world">Hola Mundo!</string>  
  5. </resources>  

法语,/values-fr/strings.xml:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="title">Mon Application</string>  
  4.     <string name="hello_world">Bonjour le monde !</string>  
  5. </resources>  

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

使用字符串资源

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

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

例如:

  1. // 从程序资源中获取字符串   
  2. String hello = getResources().getString(R.string.hello_world);  
  3.   
  4. // 为需要字符串的方法提供字符串资源   
  5. TextView textView = new TextView(this);  
  6. textView.setText(R.string.hello_world);  

在XML文件中,你可以使用@string/<string_name>这样的语法接收一个字符串资源。例如:

  1. <TextView  
  2.     android:layout_width="wrap_content"  
  3.     android:layout_height="wrap_content"  
  4.     android:text="@string/hello_world" />  

相关内容