Android可以適配不同的語言

2018-08-02 17:15 更新

編寫:Lin-H - 原文:http://developer.android.com/training/basics/supporting-devices/languages.html

把UI中的字符串存儲在外部文件,通過代碼提取,這是一種很好的做法。Android可以通過工程中的資源目錄輕松實現(xiàn)這一功能。

如果使用Android SDK Tools(詳見創(chuàng)建Android項目(Creating an Android Project))來創(chuàng)建工程,則在工程的根目錄會創(chuàng)建一個res/的目錄,目錄中包含所有資源類型的子目錄。其中包含工程的默認(rèn)文件比如res/values/strings.xml,用于保存字符串值。

創(chuàng)建區(qū)域設(shè)置目錄及字符串文件

為支持多國語言,在res/中創(chuàng)建一個額外的values目錄以連字符和ISO國家代碼結(jié)尾命名,比如values-es/是為語言代碼為"es"的區(qū)域設(shè)置的簡單的資源文件的目錄。Android會在運(yùn)行時根據(jù)設(shè)備的區(qū)域設(shè)置,加載相應(yīng)的資源。詳見Providing Alternative Resources。

若決定支持某種語言,則需要創(chuàng)建資源子目錄和字符串資源文件,例如:

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

添加不同區(qū)域語言的字符串值到相應(yīng)的文件。

Android系統(tǒng)運(yùn)行時會根據(jù)用戶設(shè)備當(dāng)前的區(qū)域設(shè)置,使用相應(yīng)的字符串資源。

例如,下面列舉了幾個不同語言對應(yīng)不同的字符串資源文件。

英語(默認(rèn)區(qū)域語言),/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>

Note:可以在任何資源類型中使用區(qū)域修飾詞(或者任何配置修飾符),比如為bitmap提供本地化的版本,更多信息見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文件中,每當(dāng)XML屬性要接受一個字符串值時,你都可以通過@string/<string_name>語法來引用字符串資源。

例如:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號