【关键字】
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>
-
getContext(this).createModuleContext 的使用方式也会报错,跟文档中给出的使用方式相比,多传了 this 作为 getContext 的参数,
报错内容如下:context TypeError: Cannot read property createModuleContext of undefined
【解决方案】
参考文档:
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%')
}
}