Android培訓—支援不同的語言

來源:互聯網
上載者:User

本文譯自:http://developer.android.com/training/basics/supporting-devices/languages.html#UseString

從你的應用程式代碼中把UI的字串提取到一個外部檔案中是一個很好的實踐,Android系統在每個Android工程中用一個資來源目錄讓這件事變的很容易。

如果你使用Android的SDK工具建立工程,該工具會在工程的頂層建立一個叫res/的目錄。在這個res/的目錄中是各種資源類型的子目錄。還有一些預設的檔案,如res/values/strings.xml,該檔案會儲存字串值。

建立語言目錄和字串檔案

要添加對多語言的支援,就要在res/目錄中添加一個包含連字號和ISO國家代碼結尾的values目錄,如,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>

注意:你可以在任何類型的資來源目錄上使用語言限定符,如提供本地化的位元影像資源。

使用字串資源

你可以在你資原始碼和其他的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檔案中,你可在任何接收字串值的XML屬性中,使用@string/<string_name>文法形式來引用字串資源,如:

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

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.