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

 【关键字】

HSP包 / context 获取 resourceManager 对象 / getContext()

【问题描述】

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

请问:

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

2、HSP包中如何获取 context 上下文?

  • HSP包内通过 createModuleContext(moduleName) 接口创建同应用中 entry 包的上下文,

提示 :Property 'createModuleContext' does not exist on type '(component?: Object) => Context'. <ArkTSCheck>

cke_783.png

  • getContext(this).createModuleContext 的使用方式也会报错,跟文档中给出的使用方式相比,多传了 this 作为 getContext 的参数,

报错内容如下:context TypeError: Cannot read property createModuleContext of undefined

cke_1296.png

【解决方案】

参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/resource-categories-and-access-0000001774119914#section10716174818441

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%')
}
}

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值