#跟着坚果学鸿蒙#资源分类与访问<六>
资源访问
单HAP包应用资源
- 通过$r或$rawfile访问资源。
对于color、float、string、plural、media、profile等类型的资源,通过$r('app.type.name')形式访问。其中,app为resources目录中定义的资源,type为资源类型,name为资源名,由开发者定义资源时确定。
对于string.json中使用多个占位符的情况,通过$r('app.string.label','aaa','bbb',444)形式访问。
对于rawfile目录资源,通过$rawfile('filename')形式访问。其中,filename为rawfile目录下文件的相对路径,文件名需要包含后缀,路径开头不可以"/"开头。
资源组目录下的“资源文件示例”显示了.json文件内容,包含color.json、string.json和plural.json,访问应用资源时需先了解.json文件的使用规范。
资源的具体使用方法如下:
//通过$r('app.type.name')访问
Text($r('app.string.string_hello'))
.fontColor($r('app.color.color_emphasize'))
.fontSize($r('app.float.text_size_headline1'))
.fontFamily($r('app.string.font_family_medium'))
.backgroundColor($r('app.color.color_palette_aux1'))
Image($r('app.media.app_icon'))
.border({
color: $r('app.color.color_palette_aux1'),
radius: $r('app.float.corner_radius_button'), width: 2
})
.margin({
top: $r('app.float.elements_margin_horizontal_m'),
bottom: $r('app.float.elements_margin_horizontal_l')
})
.height(200)
.width(300)
//对占位符,通过$r('app.string.label','aaa','bbb',444)访问
Text($r('app.string.message_notification','LiHua',2))
- 通过本应用上下文获取ResourceManager后,调用不同资源管理接口访问不同资源。例如:
getContext().resourceManager.getStringByNameSync('test')可获取字符串资源。
getContext().resourceManager.getRawFd('rawfilepath')可获取Rawfile所在hap包的descriptor信息,访问rawfile文件时需{fd, offset, length}一起使用。
跨HAP/HSP包应用资源
bundle相同,跨module访问
- 通过createModuleContext(context, moduleName)接口创建同应用中不同module的上下文,获取resourceManager对象后,调用不同资源管理接口访问不同资源。
- 通过$r或$rawfile访问资源。具体操作如下:
1.在entry的oh-package.json5文件中添加依赖。如"dependencies": {"library":"file":../library}。
2.使用字面量[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].icon.png'))
3.使用变量获取资源。示例如下:
@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))
}
}
}
系统资源
开发者可以通过主题图标库获取系统图标资源信息、通过系统资源分层设计表获取系统字体等资源信息。获取的图标资源可通过SymbolGlyph对图标颜色等进一步设置。
对于系统资源,可以通过$r('sys.type.name')的形式访问。其中,sys表示系统资源,type为资源类型,取值包括“color”、“float”、“string”、“media”、“symbol”,name为资源名称。
Text('Hello')
.fontColor($r('sys.color.ohos_id_color_emphasize'))
.fontSize($r('sys.float.ohos_id_text_size_headline1'))
.fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
.backgroundColor($r('sys.color.ohos_id_color_palette_aux1'))
Image($r('sys.media.ohos_app_icon'))
.border({
color: $r('sys.color.ohos_id_color_palette_aux1'),
radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2
})
.margin({
top: $r('sys.float.ohos_id_elements_margin_horizontal_m'),
bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')
})
.height(200)
.width(300)
更多推荐
所有评论(0)