支持不同的語言
將APP代碼中的UI字符串提取到一個外部的文件中是一個很好的慣例。Android工程下的資源目錄能輕易實現這個功能。
如果你使用Android SDK工具創建了你的工程,這個工具會在工程的頂層創建一個res/目錄。這個目錄裏面是不同類型資源的子目錄。有些是默認的文件,例如res/values/strings.xml .裏面存放的是字符串的值。
創建現場目錄和字符串文件
要支持更多的語言,需要在res/目錄下創建額外的values目錄,命名規則是:values + 連接符+ISO 國家代碼。例如:values-es.Android會根據運行時環境來加載合適的資源。
一旦你決定要支持某種語言,需要創建資源子目錄和string資源文件,例如:
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>
西班牙,/res/values-es/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<stringname="title">Mi Aplicación</string>
<stringname="hello_world">Hola Mundo!</string>
</resources>
法語, /values-fr/strings.xml
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<stringname="title">Ma Application</string>
<stringname="hello_world">Bonjour tout le Monde!</string>
</resources>
注意:在任何資源類型中,你都能使用場景限定。例如不同的場景使用不同的圖片,詳見Localization.
使用字符串資源
通過資源名字,你就可以在代碼中或者其它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>來引用字符串資源。例子:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"/>