宁睿 发表于 2025-4-3 11:59:31

鸿蒙HarmonyOS学习笔记(8)

怎样实现ArkUI组件字符串变量拼接

标题征象
例如:Text()组件的字符串变量拼接功能,怎样实现?
Text($r('app.string.EntryAbility_desc', 'Hello')) 办理措施
可以通过资源文件联合%d、%s的方式举行实现。
示例如下所示:

[*] 修改"src/main/resources/zh_CN/element/string.json"文件,对其中的一个需要变量拼接内容增加%d拼接。

{
"string": [
    {
      "name": "module_desc",
      "value": "模块描述%d"
    },
    {
      "name": "EntryAbility_desc",
      "value": "description"
    },
    {
      "name": "EntryAbility_label",
      "value": "label"
    }
]
} 修改"src/main/resources/en_US/element/string.json"文件,对其中的一个需要变量拼接内容增加%d拼接。
{
"string": [
    {
      "name": "module_desc",
      "value": "module description%d"
    },
    {
      "name": "EntryAbility_desc",
      "value": "description%d"
    },
    {
      "name": "EntryAbility_label",
      "value": "label"
    }
]
}
[*] 在页面组件中利用$r(xx)加上拼接变量进利用用。

@Entry
@Component
struct Page1 {
@State num1: number = 100;

build() {
    Row() {
      Column() {
      Text($r('app.string.module_desc', this.num1))
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
}
}
[*] 切换中英文语言时,会自动跟随语言的切换带入对应的变量信息。

单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.ohos_id_color_emphasize'))
.fontSize($r('app.float.ohos_id_text_size_headline1'))
.fontFamily($r('app.string.ohos_id_text_font_family_medium'))
.backgroundColor($r('app.color.ohos_id_color_palette_aux1'))

Image($r('app.media.ohos_app_icon'))
.border({
    color: $r('app.color.ohos_id_color_palette_aux1'),
    radius: $r('app.float.ohos_id_corner_radius_button'), width: 2
})
.margin({
    top: $r('app.float.ohos_id_elements_margin_horizontal_m'),
    bottom: $r('app.float.ohos_id_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}一起利用。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 鸿蒙HarmonyOS学习笔记(8)