鸿蒙开发中string.json资源文件中,定义一个字符串,字符串中间有s%,text使用时,第二个参数为占位符,如何也引用string.json?

鸿蒙开发中string.json资源文件中,定义一个字符串,字符串中间有s%,text使用时,第二个参数为占位符,如何也引用string.json?

-- 来自郝老师直播间

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

阅读 905
avatarAI BotBETA
在鸿蒙开发中,若你希望在 `string.json` 资源文件中定义一个包含占位符的字符串,并且占位符的值也来自 `string.json`,你可以通过以下方式实现:

1. **定义字符串资源**:
   在 `string.json` 中定义两个字符串资源,一个是包含占位符的字符串,另一个是占位符实际要引用的字符串。

{

   "with_placeholder": "This is a string with %s placeholder",
   "placeholder_value": "Hello HarmonyOS"

}


2. **在代码中动态替换**:
由于 `string.json` 本身不支持直接嵌套引用,你需要在代码中读取这两个字符串并进行拼接或格式化。

例如,在 Java 代码中,你可以这样做:

StringResourceTable resourceTable = ResourceTable.getInstance();
String withPlaceholder = resourceTable.getString(ResourceTable.String_with_placeholder);
String placeholderValue = resourceTable.getString(ResourceTable.String_placeholder_value);

String result = String.format(withPlaceholder, placeholderValue);


在 JavaScript(ArkUI)中,你可以使用模板字符串或字符串的 `replace` 方法:

let resourceTable = $r('app.string');
let withPlaceholder = resourceTable.with_placeholder;
let placeholderValue = resourceTable.placeholder_value;

let result = withPlaceholder.replace('%s', placeholderValue);


通过这种方式,你可以在 `string.json` 中定义包含占位符的字符串,并在代码中使用其他字符串资源来替换这些占位符。
1 个回答

因为第二个参数也是国际化翻译多语言的,所以不能在界面里写为定值,需要引用string.json
第二个参数用getContext(this).resourceManager.getStringSync($r(‘app.string.dfs_hotline’)),执行即可,注意,previewer无效,需要用真机去验证

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进