1. 程式人生 > >Android中的語言和字串資源

Android中的語言和字串資源

在任何情況下,從您的應用程式碼中提取 UI 字串並將其存放在外部檔案中都是個好辦法。Android 在每個 Android 專案中都提供一個資源目錄,從而簡化了這一過程。

如果您是使用 Android SDK 工具建立的專案(請閱讀建立 Android 專案),工具會在專案的頂層建立一個 res/ 目錄。此 res/ 目錄中包含用於存放各類資源的子目錄。此外,還包含幾個預設檔案(如 res/values/strings.xml),用於存放您的字串值。

建立語言區域目錄和字串檔案

如需新增對更多語言的支援,請在 內建立額外的 valuesres/ 目錄,並在目錄名稱末尾加上連字元和 ISO 語言程式碼。例如,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>

注:您可以在任何資源型別上使用語言區域限定符(或任何配置限定符),例如,您可以提供本地化版本的可繪製點陣圖。

使用字串資源

您可以使用由 元素的 name 屬性定義的資源名稱在您的原始碼和其他 XML 檔案中引用您的字串資源。

在您的原始碼中,可以使用語法 R.string. 引用字串資源。有許多方法都接受以這種方式引用的字串資源。

例如:

// 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/ 引用字串資源。

例如:

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

我的微信二維碼如下,歡迎交流討論

這裡寫圖片描述

歡迎關注《IT面試題彙總》微信訂閱號。每天推送經典面試題和麵試心得技巧

微信訂閱號二維碼如下:

這裡寫圖片描述