歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android Training - 支持不同的語言

Android Training - 支持不同的語言

日期:2017/3/1 10:13:40   编辑:Linux編程

把UI中的字符串從代碼中提取到一個外部文件中是一個好的習慣。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在適當的文件中添加字符串的值。

在運行的時候,android系統根據用戶設備中設置的當前區域使用對應的字符串資源。

例如,下面是一些不同的字符串資源,對應不同的語言。

英語(默認區域),/values/strings.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string name="title">My Application</string>
  4. <string name="hello_world">Hello World!</string>
  5. </resources>

西班牙語,/values-es/strings.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string name="title">Mi Aplicación</string>
  4. <string name="hello_world">Hola Mundo!</string>
  5. </resources>

法語,/values-fr/strings.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string name="title">Mon Application</string>
  4. <string name="hello_world">Bonjour le monde !</string>
  5. </resources>

提示:你可以在任何資源類型上使用區域限定符,比如你可以為不同的區域提供不同的圖片,想了解更多,請看Localization.

使用字符串資源

你可以在源代碼和其他XML文件中通過資源名稱引用這些資源,這個名稱是通過元素的name屬性定義的。

在代碼中,你可以參考類似R.string.這樣的語法調用,下面的函數中就是通過這個方法去調用一個字符串資源的。

例如:

  1. // 從程序資源中獲取字符串
  2. String hello = getResources().getString(R.string.hello_world);
  3. // 為需要字符串的方法提供字符串資源
  4. TextView textView = new TextView(this);
  5. textView.setText(R.string.hello_world);

在XML文件中,你可以使用@string/<string_name>這樣的語法接收一個字符串資源。例如:

  1. <TextView
  2. android:layout_width="wrap_content"
  3. android:layout_height="wrap_content"
  4. android:text="@string/hello_world" />
Copyright © Linux教程網 All Rights Reserved