支持不同语言

官网翻译:http://developer.android.com/intl/zh-cn/training/basics/supporting-devices/languages.html


从你的应用程序代码中提取UI字符串并保存到外部文件是一种很好的做法,在安卓中使用一个资源目录来使其变的很容易


如果你使用android SDK创建项目,这工具会在顶层目录下面创建一个res文件夹,然后会创建res/values/string.xml文件来保存你的字符串值


创建本地化的目录和字符串文件

为了支持更多的语言,在res文件夹下创建额外的目录,并在目录名称末尾添加ISO语言代码附加值。例如 value-es是包含西班牙语字符串的目录。android会根据设备运行时的语言环境加载对应的资源。


一旦你决定了你会支持的语言,创建资源子目录和字符串资源文件。例如:
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>

西班牙语, /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>
注意:您可以在任何资源类型使用语言环境限定符(或任何配置预选赛) ,如果你想为你绘制的位图本地化,欲了解更多信息,请参见本地化。http://developer.android.com/intl/zh-cn/guide/topics/resources/localization.html

使用String资源
你可以在你的源码和xml文件中使用这些string资源,在源码中通过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" />



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章