支持不同語言

官網翻譯:http://developer.android.com/intl/zh-cn/training/basics/supporting-devices/languages.html


從你的應用程序代碼中提取UI字符串並保存到外部文件是一種很好的做法,在安卓中使用一個資源目錄來使其變的很容易


如果你使用android SDK創建項目,這工具會在頂層目錄下面創建一個res文件夾,然後會創建res/values/string.xml文件來保存你的字符串值


創建本地化的目錄和字符串文件

爲了支持更多的語言,在res文件夾下創建額外的目錄,並在目錄名稱末尾添加ISO語言代碼附加值。例如 value-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>
注意:您可以在任何資源類型使用語言環境限定符(或任何配置預選賽) ,如果你想爲你繪製的位圖本地化,欲瞭解更多信息,請參見本地化。http://developer.android.com/intl/zh-cn/guide/topics/resources/localization.html

使用String資源
你可以在你的源碼和xml文件中使用這些string資源,在源碼中通過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中則通過一下方式使用:@string/string_name,如下所示

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章