HarmonyOS 关于在HSP包中获取应用资源对应字符串的问题

由于在工具类中需要获取应用资源 $r(‘app.type.name’) 对应的字符串内容,因此需要通过 context 获取 resourceManager 对象,但是通过 getContext() 函数创建上下文时报错,请问:

1、获取应用资源对应的字符串是否只能通过 resourceManager 对象调用相关函数获取?有没有简单点儿的方法?

2、HSP 包中如何获取 context 上下文?由于是工具类,无法直接通过 this 获取,通过 getContext() 函数创建无效,返回 undefined

HarmonyOS
2024-12-27 17:35:49
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
shlp

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/resource-categories-and-access-V5

bundle相同,跨module访问需要通过createModuleContext(moduleName)接口创建同应用中不同module的上下文,获取resourceManager对象后,调用不同接口访问不同资源。

参考如下demo:

//library包:
export function get(context: Context) {
  let a:string = ''
  try{
    a = context.createModuleContext('entry').resourceManager.getStringByNameSync('EntryAbility_label') //获取library下string.json中EntryAbility_label字段的值
  }catch (e){
    console.log('')
  }
  return a
}


//entry包:
@Entry
@Component
export struct MainPage {
  @State message: string = 'Hello World';
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            let a = get(getContext(this))
            promptAction.showToast({
              message: a.toString()
            });
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
  • 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.
分享
微博
QQ
微信
回复
2024-12-27 19:08:26


相关问题
关于加密字符串相关问题
744浏览 • 1回复 待解决
HarmonyOS 获取资源文件配置字符串
410浏览 • 1回复 待解决
关于鸿蒙arkts解析json字符串问题
1268浏览 • 2回复 待解决
HarmonyOS字符串替换问题
1375浏览 • 1回复 待解决
关于字符串分割和重组处理
4976浏览 • 1回复 待解决
HarmonyOS 字符串编码问题
457浏览 • 1回复 待解决
HarmonyOS 替换字符串问题
716浏览 • 1回复 待解决
HarmonyOS ArkTSmap如何转成字符串
460浏览 • 1回复 待解决
HarmonyOS $r 字符串替换问题
1440浏览 • 1回复 待解决
HarmonyOS string字符串截取问题
633浏览 • 1回复 待解决
HarmonyOS SVG字符串加载问题
485浏览 • 1回复 待解决