【android官方文檔】android 多國語言支持 國際化

             如轉載請註明出處http://blog.csdn.net/ethanchiu/article/details/19542401

支持不同的語言

     將UI的strings從app代碼中提取出來,並把他們放到一個外部文件中,這是一個好的方式。android通過一個項目中的資源文件使得這些很容易做到。
     在項目的頂層有個res/目錄,在這個目錄裏有很多子目錄。有些默認的文件比如res/values/strings.xml,它保存了你的string值。
     

創建本地目錄和String文件

     爲了支持更多的語言,創建額外的values目錄,這個values目錄的名字後面跟着連字符和國家iso編碼代號。比如,values-es/這個目錄包含的資源是提供給爲本地語言爲“es”的資源。android會根據設備運行時的本地設置讀取合適的資源。

     一旦你決定了你要支持的語言,創建子目錄和string資源文件。比如

MyProject/
    res/
       values/
           strings.xml
       values-es/
           strings.xml
       values-fr/
           strings.xml

 將string值放到恰當的文件中。

     在運行的時候,android系統使用合適的string資源設置是基於當前用戶的本地設置。

     比如,下面是不同語言對應不同的string資源。
     英語(默認的本地設置),/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/string.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/string.xml:

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

使用String資源     

可以在代碼和xml文件中通過<string>元素中的name屬性定義的資源名字引用string資源。

     在代碼中,可以使用R.string.<string_name>這個語法引用string資源。有很多訪問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文件中,可以通過@string/<string_name>語法引用string資源
     比如:

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

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