Android學習路線(十七)支持不同設備——支持不同的語言

將UI中的字符串從應用代碼中提取出來並存放在額外的文件中是一個好習慣。Android在每個項目中通過一個資源目錄讓這件事變得很簡單。

如果你使用Android SDK工具創建了一個項目,這個工具會在你的項目的頂級目錄下創建一個 res/ 目錄。在這個目錄下有很多子目錄用來存放多種類型的資源。同樣有一些默認的文件,例如res/values/strings.xml,用來存放字符串。

創建區域目錄以及字符串文件


爲了支持更多的語言,在res/目錄下創建附加的values目錄,文件名使用values加上連字符號再加上國際標準化語言碼。例如,values-es/ 目錄包含了語言碼爲“es”的區域的簡單的資源文件。Android系統會根據設備運行時設置的區域設定來加載適當的資源文件。更多的信息,請參閱Providing Alternative Resources

一旦你決定要支持這種語言,要爲它創建相應的資源目錄以及字符串文件。例如:

MyProject/
    res/
       values/
           strings.xml
       values-es/
           strings.xml
       values-fr/
           strings.xml

爲每個區域的文件添加字符串的值。

在運行時,Android系統會根據設備運行時設置的區域設定來加載適當的資源文件。

例如,下面是不同語言的不同資源文件。

English (默認區域), /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>

Spanish, /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>

French, /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>

提示: 你可以爲任何類型的資源使用區域限制(或者任何配置限制),例如如果你想要爲不同的區域提供不同的bitmap drawable。更多信息,請參閱Localization

使用字符串資源


你可以使用在<string> 元素的name 屬性中指定的字符串名稱在代碼或者其他XML文件中引用該資源。

在你的源代碼中,你可以使用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" />
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章