注:本文翻譯自Google官方的Android Developers Training文檔,譯者技術(shù)一般,由于喜愛安卓而產(chǎn)生了翻譯的念頭,純屬個(gè)人興趣愛好。
原文鏈接: http://developer.android.com/training/basics/supporting-devices/languages.html
將UI字符串從你應(yīng)用的代碼中提取出來,并將它們放置在一個(gè)外部的文件中是一個(gè)值得長期保持的習(xí)慣。Android使得這件事情變的簡單,在每個(gè)Andorid項(xiàng)目工程中,都有一個(gè)放置資源的目錄。
如果你通過Android SDK Tools創(chuàng)建了你的項(xiàng)目工程( Creating an Android Project ,對應(yīng)博客鏈接: http://www.cnblogs.com/jdneo/p/3438347.html ),這個(gè)工具會(huì)在項(xiàng)目的頂層創(chuàng)建一個(gè)“ /res ”目錄。在這個(gè)目錄下的所有子目錄對應(yīng)了不同類型的資源。這里面也有一些默認(rèn)的文件比如: res/values/strings.xml ,這個(gè)文件存放了你的字符資源。
?
一). 創(chuàng)建地區(qū)目錄和字符串文件
為了支持更多語言,在“ res/ ”下創(chuàng)建額外的“ values ”文件,文件名的最后還包含一個(gè)橫線“-”,和國家的國際標(biāo)準(zhǔn)碼。例如:“ values-es/ ”這一目錄下存放的是一些適配地區(qū)碼為“es”的簡單資源。Android會(huì)在運(yùn)行時(shí)根據(jù)設(shè)備的地區(qū)設(shè)置來恰當(dāng)?shù)丶虞d資源。
一旦你決定好了要支持哪些語言,你就可以創(chuàng)建資源的子目錄和字符串資源文件,例如:
MyProject/
res/
values/
strings.xml
values-es/
strings.xml
values-fr/
strings.xml
然后將字符串的值根據(jù)不同地區(qū)添加到對應(yīng)的文件中。
在運(yùn)行時(shí),Android系統(tǒng)會(huì)根據(jù)當(dāng)前設(shè)備的地區(qū)設(shè)置信息來使用對應(yīng)的字符串資源集。
例如:下面是不同語言所對應(yīng)的不同的字符串資源文件:
英語(默認(rèn)地區(qū)), /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:
你可以在任何類型的資源上使用地區(qū)適配符(或其他任何設(shè)置符(configuration qualifer)),比如你可以以此將你的位圖資源根據(jù)地區(qū)不同而使用不同的版本。更多信息可以閱讀: Localization
?
二). 使用字符串資源
你可以在你的源碼或其他XML文件中,使用 <string>標(biāo)簽中的“ name ”屬性字段定義的資源名,對字符串資源進(jìn)行引用。
在你的源碼中,你可以通過如下語法:“ R.string.<string_name> ”來引用字符串資源。有很多方法會(huì)接受以這種方式接受一個(gè)字符串資源作為參數(shù)。
例如:
// 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文件中,當(dāng)XML屬性字段接受一個(gè)字符串值時(shí),你可以使用如下語法:“ @string/<string_name> ”來引用字符串資源。
例如:
< TextView android:layout_width ="wrap_content" android:layout_height ="wrap_content" android:text ="@string/hello_world" />
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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