注:本文翻譯自Google官方的Android Developers Training文檔,譯者技術一般,由于喜愛安卓而產生了翻譯的念頭,純屬個人興趣愛好。
原文鏈接: http://developer.android.com/training/basics/supporting-devices/languages.html
將UI字符串從你應用的代碼中提取出來,并將它們放置在一個外部的文件中是一個值得長期保持的習慣。Android使得這件事情變的簡單,在每個Andorid項目工程中,都有一個放置資源的目錄。
如果你通過Android SDK Tools創建了你的項目工程( Creating an Android Project ,對應博客鏈接: http://www.cnblogs.com/jdneo/p/3438347.html ),這個工具會在項目的頂層創建一個“ /res ”目錄。在這個目錄下的所有子目錄對應了不同類型的資源。這里面也有一些默認的文件比如: res/values/strings.xml ,這個文件存放了你的字符資源。
?
一). 創建地區目錄和字符串文件
為了支持更多語言,在“ res/ ”下創建額外的“ 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 >
Note:
你可以在任何類型的資源上使用地區適配符(或其他任何設置符(configuration qualifer)),比如你可以以此將你的位圖資源根據地區不同而使用不同的版本。更多信息可以閱讀: Localization
?
二). 使用字符串資源
你可以在你的源碼或其他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" />
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
