本文譯自:http://developer.android.com/training/basics/supporting-devices/languages.html#UseString
從你的應用程式代碼中把UI的字串提取到一個外部檔案中是一個很好的實踐,Android系統在每個Android工程中用一個資來源目錄讓這件事變的很容易。
如果你使用Android的SDK工具建立工程,該工具會在工程的頂層建立一個叫res/的目錄。在這個res/的目錄中是各種資源類型的子目錄。還有一些預設的檔案,如res/values/strings.xml,該檔案會儲存字串值。
建立語言目錄和字串檔案
要添加對多語言的支援,就要在res/目錄中添加一個包含連字號和ISO國家代碼結尾的values目錄,如,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>
注意:你可以在任何類型的資來源目錄上使用語言限定符,如提供本地化的位元影像資源。
使用字串資源
你可以在你資原始碼和其他的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檔案中,你可在任何接收字串值的XML屬性中,使用@string/<string_name>文法形式來引用字串資源,如:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"/>