Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Training:讓應用支援多國語言

編輯:關於 Android 程式設計

把介面上的字串從程式碼裡搬到外部資源檔,是很值得養成的好習慣。Android 為此準備了專屬的資源目錄機制。

建立語言專屬的資源資料夾

用 SDK 工具建立專案時,工具會在根目錄產生 res/,其中的子資料夾代表不同資源類型,例如 res/values/strings.xml 就是存放預設字串的地方。

要支援多國語言,做法是在 res/ 下建立以「values-」加上 ISO 語言代碼命名的資料夾。例如 values-es/ 存放的是語言代碼為 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>

小提醒:區域限定符不只用在字串上,你也可以為不同區域準備不同圖片,細節可參考官方 Localization 章節。

在程式碼與版面檔中引用

資源的名稱由 <string> 的 name 屬性決定,之後就能在 Java 與 XML 中跨處引用。

Java 中使用 R.string.<string_name>:

// 從資源取出字串
String hello = getResources().getString(R.string.hello_world);

// 直接餵給需要字串的方法
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" />

只要養成「不寫死字串」的習慣,日後要加語言時,往往只需補一個 XML 檔,不必回頭翻整份程式碼。

作者:lixiang0522

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved