场景一:访问模块内资源
通过"$r"或"$rawfile"引用资源。对于“color”、“float”、“string”、“plural”、“media”、“profile”等类型的资源,通过"$r('app.type.name')"形式引用。其中,app为resources目录中定义的资源;type为资源类型或资源的存放位置;name为资源名,开发者定义资源时确定。
对于rawfile目录资源,通过"$rawfile('filename')"形式引用。
使用$r进行string资源引用。
Text($r("app.string.mystring"))
在rawfile下的资源可以通过$rawfile+文件名访问。
Image($rawfile("img.jpg"))
场景二:跨HAP/HSP包应用资源。
方式一:通过createModuleContext(moduleName)接口创建同应用中不同module的上下文,获取resourceManager对象后,调用不同接口访问不同资源。
getContext(this).createModuleContext(moduleName).resourceManager.getStringByNameSync('app.string.XXX')
方式二:通过"$r"或"$rawfile"引用资源(api12支持的能力)。 1.[hsp].type.name获取资源。其中,hsp为hsp模块名,type为资源类型,name为资源名称。
Text($r('[hsp].string.test_string'))
.fontSize($r('[hsp].float.font_size'))
.fontColor($r('[hsp].color.font_color'))
Image($rawfile('[hsp].oneFile/twoFile/icon.png'))
使用变量获取资源。
@Entry
@Component
struct Index {
text: string = '[hsp].string.test_string';
fontSize: string = '[hsp].float.font_size';
fontColor: string = '[hsp].color.font_color';
image: string = '[hsp].media.string';
rawfile: string = '[hsp].icon.png';
build() {
Row() {
Text($r(this.text))
.fontSize($r(this.fontSize))
.fontColor($r(this.fontColor))
Image($r(this.image))
Image($rawfile(this.rawfile))
}
}
}
说明:hsp包名必须写在[]内,”rawfile“下有多层目录,需要从”rawfile“下面第一个目录开始写,如“$rawfile\('\[hsp\].oneFile/twoFile/icon.png'\)”,使用"$r"和"$rawfile"跨包访问HSP包资源无法提供编译时的资源校验,需要开发者自行保证使用资源存在于对应包中。
场景三:HSP包的资源导出引用。
1、创建HSP,新建模块,选择shared library。
2、导出需要使用的资源。导出ResManager1,以便其他模块获取到hsp中的resource资源。
export class ResManager1{
static getPic(): Resource{
return $r('app.media.11');
}
static getDesc(): Resource{
return $r('app.string.shared_desc1');
}
}
在模块下的index.ets导出资源。
3、引用资源。在引用方模块的oh-package.json5下添加依赖,执行install。
Import加载并使用。
import {ResManager1}from 'hsp'
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(ResManager1.getDesc())
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
场景四:HAR包的资源导出引用
1、新建模块,选择static library。
2、export使用的资源,并在模块下的index.ets导出。
3、build出har包。
Build完成后会在模块下生成.har文件。
4、引用har包,在引用方oh-package.json5下添加依赖,依赖需要到.har文件,执行install。
5、import 后调用har中的资源。
import {ResManager}from 'har'
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Image(ResManager.getPic()).width(50)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。