OpenHarmony國(guó)際化I18n開(kāi)發(fā)范例
想了解更多關(guān)于開(kāi)源的內(nèi)容,請(qǐng)?jiān)L問(wèn):
概念介紹
在開(kāi)發(fā)應(yīng)用中可能會(huì)遇到多國(guó)家多地區(qū)場(chǎng)景,應(yīng)用要提供不同的語(yǔ)言、時(shí)間、時(shí)區(qū)給目標(biāo)用戶(hù)和市場(chǎng),開(kāi)發(fā)者往往需要提供多個(gè)不同版本以保證不同地區(qū)用戶(hù)方便使用。
本例基于國(guó)際化示例應(yīng)用,為大家介紹I18n組件,該組件提供系統(tǒng)相關(guān)的或者增強(qiáng)的國(guó)際化能力。
接口
I18n官方文檔 @ohos.i18n。
類(lèi)名 | 接口名稱(chēng) | 描述 |
System | getDisplayCountry(country:string,locale:string,sentenceCase?:boolean):string<sup>9+</sup> | 獲取國(guó)家的本地化表示。 |
System | getDisplayLanguage(language:string,locale:string,sentenceCase?:boolean):string<sup>9+</sup> | 獲取語(yǔ)言的本地化表示。 |
System | getSystemLanguages():Array<string><sup>9+</sup> | 獲取系統(tǒng)語(yǔ)言列表。 |
System | getSystemCountries(language: string):Array<string><sup>9+</sup> | 獲取針對(duì)輸入語(yǔ)言系統(tǒng)支持的國(guó)家或地區(qū)列表。 |
System | isSuggested(language: string, region?: string): boolean<sup>9+</sup> | 判斷當(dāng)前語(yǔ)言和地區(qū)是否匹配 |
System | getSystemLanguage():string<sup>9+</sup> | 獲取系統(tǒng)語(yǔ)言。 |
System | setSystemLanguage(language: string)<sup>9+</sup> | 設(shè)置系統(tǒng)語(yǔ)言。 |
System | getSystemRegion():string<sup>9+</sup> | 獲取系統(tǒng)地區(qū)。 |
System | setSystemRegion(region: string)<sup>9+</sup> | 設(shè)置系統(tǒng)地區(qū)。 |
System | getSystemLocale():string<sup>9+</sup> | 獲取系統(tǒng)Locale。 |
System | setSystemLocale(locale: string)<sup>9+</sup> | 設(shè)置系統(tǒng)Locale。 |
System | is24HourClock():boolean<sup>9+</sup> | 判斷系統(tǒng)時(shí)間是否為24小時(shí)制。 |
System | set24HourClock():boolean<sup>9+</sup> | 修改系統(tǒng)時(shí)間的24小時(shí)制設(shè)置。 |
System | addPreferredLanguage(language: string, index?: number)<sup>9+</sup> | 在系統(tǒng)偏好語(yǔ)言列表的指定位置添加偏好語(yǔ)言。 |
System | removePreferredLanguage(index: number)<sup>9+</sup> | 刪除系統(tǒng)偏好語(yǔ)言列表中指定位置的偏好語(yǔ)言。 |
System | getPreferredLanguageList()<sup>9+</sup> | 獲取系統(tǒng)偏好語(yǔ)言列表。 |
System | getFirstPreferredLanguage()<sup>9+</sup> | 獲取系統(tǒng)偏好語(yǔ)言列表中的第一個(gè)偏好語(yǔ)言。 |
System | getAppPreferredLanguage()<sup>9+</sup> | 獲取應(yīng)用偏好語(yǔ)言。 |
System | setUsingLocalDigit(flag: boolean)<sup>9+</sup> | 設(shè)置系統(tǒng)是否使用本地?cái)?shù)字。 |
System | getUsingLocalDigit()<sup>9+</sup> | 判斷系統(tǒng)是否使用本地?cái)?shù)字。 |
isRTL(locale:string):boolean<sup>9+</sup> | locale對(duì)應(yīng)的語(yǔ)言是否為從右到左語(yǔ)言。 |
具體實(shí)現(xiàn)
配置文件
應(yīng)用需要在項(xiàng)目的module.json5配置文件中逐個(gè)聲明所需的權(quán)限,否則應(yīng)用將無(wú)法獲取授權(quán)。
在配置文件的requestPermissions屬性數(shù)組中配置所需的權(quán)限,包含3個(gè)屬性。
{
...
"requestPermissions": [
{
"name": "ohos.permission.UPDATE_CONFIGURATION"
},
{
"name": "ohos.permission.SET_TIME_ZONE"
},
{
"name": "ohos.permission.SET_TIME"
}
]
}
- 更新配置權(quán)限:ohos.permission.UPDATE_CONFIGURATION
- 設(shè)置時(shí)區(qū)權(quán)限:ohos.permission.SET_TIME_ZONE
- 設(shè)置系統(tǒng)時(shí)間權(quán)限:ohos.permission.SET_TIME
引入I18n模塊
import i18n from '@ohos.i18n';
語(yǔ)言和地區(qū)
- 使用getSystemRegion和getSystemLocale分別獲取當(dāng)前系統(tǒng)地區(qū)和系統(tǒng)區(qū)域,并傳入getDisplayCountry獲取指定國(guó)家的本地化顯示文本。
this.currentRegion = i18n.System.getDisplayCountry(i18n.System.getSystemRegion(), i18n.System.getSystemLocale());
- 使用getSystemLanguage獲取當(dāng)前系統(tǒng)支持的語(yǔ)言列表。
this.localLanguage = i18n.System.getSystemLanguage();
- 使用getSystemCountries方法獲取針對(duì)輸入語(yǔ)言系統(tǒng)支持的國(guó)家或地區(qū)列表,隨后可以遍歷列表,并且調(diào)用isSuggested方法判斷當(dāng)前語(yǔ)言和地區(qū)是否匹配。
try {
this.countryIds = i18n.System.getSystemCountries(this.currentRegion);
} catch (err) {
Logger.error(`getSystemCountries failed, code is ${err.code}, message is ${err.message}`);
}
this.countryIds.forEach(id => {
let country = i18n.System.getDisplayCountry(id, this.localLanguage);
this.countries.push({ key: country, value: '' });
let isSuggested: boolean;
try {
isSuggested = i18n.System.isSuggested(this.localLanguage, id);
} catch (err) {
Logger.error(`isSuggested failed, code is ${err.code}, message is ${err.message}`);
}
if (isSuggested) {
this.suggestIds.push(id);
this.suggestCounties.push({ key: country, value: '' });
}
})
實(shí)現(xiàn)某時(shí)區(qū)城市在該區(qū)域的本地化顯示列表:
使用getAvailableZoneCityIDs獲取系統(tǒng)支持的時(shí)區(qū)城市ID。
使用getCityDisplayName格式化。
getTimeZoneSrc() {
this.timeZoneSrc = [];
let zoneCityIDs = i18n.TimeZone.getAvailableZoneCityIDs();
for (let zoneCityId of zoneCityIDs) {
let cityDisplayName = i18n.TimeZone.getCityDisplayName(zoneCityId, "zh-Hans");
let timeZone = i18n.TimeZone.getTimezoneFromCity(zoneCityId);
this.timeZoneSrc.push({
key: timeZone.getID(),
timeZone: timeZone,
display: cityDisplayName
});
};
}
日期和時(shí)間
- 引入systemDateTime模塊獲取當(dāng)前系統(tǒng)時(shí)間和時(shí)區(qū)。
- 引入Intl模塊,該模塊提供基礎(chǔ)的應(yīng)用國(guó)際化能力,包括時(shí)間日期格式化、數(shù)字格式化、排序等。
import systemDateTime from '@ohos.systemDateTime';
import Intl from '@ohos.intl';
systemDateTime模塊官方文檔@ohos.systemDateTimeintl模塊官方文檔@ohos.intl。
- 編寫(xiě)格式化時(shí)間方法。
Intl.DateTimeFormat方法用來(lái)創(chuàng)建時(shí)間日期格式化對(duì)象。
使用時(shí)間日期格式化對(duì)象的format方法格式化時(shí)間日期字符串。
getDateString() {
let locale = i18n.System.getSystemLocale();
let language = i18n.System.getSystemLanguage();
let params = [language, locale];
let dateFormat = new Intl.DateTimeFormat(params, options);
let date = new Date();
let formatString = dateFormat.format(date);
if (language === 'zh-Hans') {
let format = formatString.split(' ');
return [format[0], format[1]];
} else {
let format = formatString.split(', ');
return [`${format[0]}, ${format[1]}`, format[2]];
}
}
- 格式化時(shí)區(qū):
getRawOffset方法用來(lái)獲取時(shí)區(qū)對(duì)象表示的時(shí)區(qū)與UTC時(shí)區(qū)的偏差。
getSystemLanguage方法獲取系統(tǒng)語(yǔ)言。
getDisplayName方法用來(lái)獲取時(shí)區(qū)對(duì)象的本地化表示。
getTimeZoneString(timeZone: i18n.TimeZone) {
let offset = timeZone.getRawOffset();
return `GMT${offset > 0 ? '+' : '-'}${this.getTimeString(offset)} ${timeZone.getDisplayName(i18n.System.getSystemLanguage())}`;
}
上述代碼中通過(guò)判斷偏差來(lái)格式化時(shí)區(qū)顯示。
- 獲取系統(tǒng)時(shí)間后調(diào)用I18n的getTimeZone方法獲取系統(tǒng)時(shí)區(qū)并使用上述方法格式化。
getTimeDisplay() {
let timeZone = await systemTime.getTimezone();
let zone = i18n.getTimeZone(timeZone);
this.timeZone = this.getTimeZoneString(zone);
let timeInfo = this.getDateString();
this.date = timeInfo[0];
this.time = timeInfo[1];
}
區(qū)域格式示例
本模塊進(jìn)入界面展示當(dāng)前區(qū)域,當(dāng)前系統(tǒng)語(yǔ)言下的時(shí)間、數(shù)字、貨幣、百分比、單復(fù)數(shù)、屏幕方向等信息的格式化顯示。
build() {
Column() {
TitleBar({ hasBackPress: true, title: $r('app.string.format_example') })
this.TextView({ text: this.language })
Column() {
this.TextView({ text: this.date })
this.TextView({ text: this.time })
ForEach(this.numberFormat, (item, index) => {
this.TextView({ text: item });
}, item => item)
this.TextView({ text: this.pluralFormat })
this.TextView({ text: this.timeZoneDetect })
this.TextView({ text: this.normalizer })
this.TextView({ text: this.mDirection })
}
頁(yè)面代碼中的language、data和time已經(jīng)在上述方法中獲取到,下面分別看一下剩下的數(shù)據(jù)如何獲取。
- numberFormat
getNumberFormatString() {
let currentLocale = new Intl.Locale();
let locale = i18n.System.getSystemLocale();
let numfmt = new Intl.NumberFormat();
let options = numfmt.resolvedOptions();
options.locale = locale;
options.numberingSystem = currentLocale.numberingSystem;
options.currency = 'CNY';
options.currencySign = 'symbol';
options.localeMatcher = 'best fit';
options.style = 'decimal';
let params = [i18n.System.getSystemLanguage(), locale];
let numberFormat = new Intl.NumberFormat(params, options);
options.style = 'currency';
let currencyFormat = new Intl.NumberFormat(params, options);
options.style = 'percent';
let percentFormat = new Intl.NumberFormat(params, options);
// 此處返回的只是一個(gè)示例,因此1234567,123456,78.9并不具有實(shí)際意義
return [numberFormat.format(1234567), currencyFormat.format(123456), percentFormat.format(78.9)];
}
該方法主要使用Intl.NumberFormat()方法創(chuàng)建數(shù)字格式化對(duì)象。
示例:
// 使用 en-GB locale創(chuàng)建NumberFormat對(duì)象,style設(shè)置為decimal,notation設(shè)置為scientific
let numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"});
NumberFormat對(duì)象中resolvedOptions方法用來(lái)獲取該對(duì)象的格式化選項(xiàng)。
- NumberFormat對(duì)象的部分選項(xiàng)
名稱(chēng) | 類(lèi)型 | 可讀 | 可寫(xiě) | 說(shuō)明 |
locale | string | 是 | 否 | 區(qū)域參數(shù), 如:“zh-Hans-CN”。locale屬性默認(rèn)值為系統(tǒng)Locale。 |
currency | string | 是 | 是 | 貨幣單位, 如:“EUR”,“CNY”,"USD"等。 |
currencySign | string | 是 | 是 | 貨幣單位的符號(hào)顯示,取值包括: “symbol”,“narrowSymbol”,“code”,“name” 。currencySign屬性默認(rèn)值為standard。 |
localeMatcher | string | 是 | 是 | 要使用的區(qū)域匹配算法,取值包括:“l(fā)ookup”, “best fit”。localeMatcher屬性默認(rèn)值為best fit。 |
style | string | 是 | 是 | 數(shù)字的顯示格式,取值包括:“decimal”, “currency”, “percent”, “unit”。style屬性默認(rèn)值為decimal。 |
numberingSystem | string | 是 | 是 | 數(shù)字系統(tǒng),取值包括:“adlm”, “ahom”, “arab”, “arabext”, “bali”, “beng”, “bhks”, “brah”, “cakm”, “cham”, “deva”, “diak”, “fullwide”, “gong”, “gonm”, “gujr”, “guru”, “hanidec”, “hmng”, “hmnp”, “java”, “kali”, “khmr”, “knda”, “l(fā)ana”, “l(fā)anatham”, “l(fā)aoo”, “l(fā)atn”, “l(fā)epc”, “l(fā)imb”, “mathbold”, “mathdbl”, “mathmono”, “mathsanb”, “mathsans”, “mlym”, “modi”, “mong”, “mroo”, “mtei”, “mymr”, “mymrshan”, “mymrtlng”, “newa”, “nkoo”, “olck”, “orya”, “osma”, “rohg”, “saur”, “segment”, “shrd”, “sind”, “sinh”, “sora”, “sund”, “takr”, “talu”, “tamldec”, “telu”, “thai”, “tibt”, “tirh”, “vaii”, “wara”, “wcho”。numberingSystem屬性默認(rèn)值為locale的默認(rèn)數(shù)字系統(tǒng)。 |
pluralFormat 復(fù)數(shù)字符串。
首先引入common模塊。
import common from '@ohos.app.ability.common';
調(diào)用getPluralStringValue,根據(jù)指定數(shù)量獲取指定ID字符串表示的單復(fù)數(shù)字符串。
getPluralString(id: number, num: number) {
let context = getContext(this) as common.UIAbilityContext;
let plural = await context.resourceManager.getPluralStringValue(id, num);
return pluralFormat;
}
resourceManager官方文檔@ohos.resourceManager。
- timeZoneDetect
調(diào)用getTimezonesByLocation創(chuàng)建某經(jīng)緯度對(duì)應(yīng)的時(shí)區(qū)對(duì)象數(shù)組。
const LONGITUDE = 116.20;
const LATITUDE = 39.56;
getTimeZoneDetect() {
this.timeZoneDetect = await ResourceUtil.getString($r('app.string.coordinate').id);
this.timeZoneDetect += '(' + LONGITUDE + ',' + LATITUDE + ') ' +
i18n.TimeZone.getTimezonesByLocation(LONGITUDE, LATITUDE)[0].getDisplayName();
}
- normalizer
調(diào)用Normalizer.getInstance獲取文本正則化對(duì)象。
getNormalizer() {
let nl = i18n.Normalizer.getInstance(i18n.NormalizerMode.NFC);
this.normalizer = '\u1100 +\u1161 +\u11A8 = ' + nl.normalize('\u1100\u1161\u11A8');
}
- mDirection
調(diào)用getDirection方法獲取設(shè)備的配置,拿到屏幕方向?qū)傩浴?/li>
async getDirection() {
let context = getContext(this) as common.UIAbilityContext;
let configuration = await context.resourceManager.getConfiguration();
if (configuration.direction === 1) { // 1代表Horizontal,0代表Vertical
return 'Horizontal';
} else {
return 'Vertical';
}
}
}