HarmonyOS resourceManager.getStringSync如何国际化?

HarmonyOS
2024-12-19 16:58:52
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
aquaa

参考代码:

//index文件
import I18n from '@ohos.i18n';
import { common } from '@kit.AbilityKit';

@Component
@Entry
struct Index {
  status: number = 1
  context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext

  changeLanguage() {
    try {
      let contextStr = this.context.resourceManager.getStringSync($r('app.string.Language_change').id)
      console.log("11" + contextStr)
    } catch (error) {
      let code = (error as BusinessError).code;
      let message = (error as BusinessError).message;
      console.error(`getStringSync failed, error code: ${code}, message: ${message}.`);
    }
  }

  aboutToAppear(): void {
    this.changeLanguage();
  }

  build() {
    Column() {
      Text($r('app.string.Language_change'))
      Button('改变语言')
        .onClick(() => {
          if (this.status == 0) {
            I18n.System.setAppPreferredLanguage('zh-Hans');
            this.status = 1
          } else {
            I18n.System.setAppPreferredLanguage('en-Latn-US');
            this.status = 0
          }
          setTimeout(() => {
            this.changeLanguage();
          }, 5000)
        })
    }
    .margin({
      top: 70
    })
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.

然后在resources目录下配置base/element/string.json文件en_US/element/string.json文件zh_US/element/string.json文件下配置对应的语言最后在IDE导航菜单Run/Edit Configurations/Installation Options/Keep Application Data勾选

分享
微博
QQ
微信
回复
2024-12-19 17:59:40


相关问题
HarmonyOS 国际化方案
738浏览 • 1回复 待解决
HarmonyOS 国际化如何切换
741浏览 • 1回复 待解决
HarmonyOS saveButton国际化问题
820浏览 • 1回复 待解决
HarmonyOS 权限弹窗国际化适配
619浏览 • 1回复 待解决
HarmonyOS 多语言国际化咨询
345浏览 • 1回复 待解决
HarmonyOS getStringSync无法格式字符串
555浏览 • 1回复 待解决
HarmonyOS resourceManager使用问题
1030浏览 • 1回复 待解决
HarmonyOS 如何获取hsp下的resourceManager
618浏览 • 1回复 待解决