HarmonyOS鸿蒙Next中$r("app.string.test")获取的字符串资源怎么转换成字符串?

HarmonyOS鸿蒙Next中$r(“app.string.test”)获取的字符串资源怎么转换成字符串? 我想要对$r(“app.string.test”)获取的字符串进行处理,应该怎么做?

4 回复

ResourceManager里有同步的方法:

/**
 * Obtains string resources associated with a specified resource ID.
 *
 * @param resId Indicates the resource ID.
 * @returns Returns the character string corresponding to the resource ID.
 * @throws { BusinessError } 401 - If the input parameter invalid.
 * @throws { BusinessError } 9001001 - If the resId invalid.
 * @throws { BusinessError } 9001002 - If the resource not found by resId.
 * @throws { BusinessError } 9001006 - If the resource re-ref too much.
 * @since 9
 */
getStringSync(resId: number): string;
/**
 * Obtains string resources associated with a specified resource object.
 *
 * @param resource Indicates the resource object.
 * @returns Returns the character string corresponding to the resource object.
 * @throws { BusinessError } 401 - If the input parameter invalid.
 * @throws { BusinessError } 9001001 - If the module resId invalid.
 * @throws { BusinessError } 9001002 - If the resource not found by module resId.
 * @throws { BusinessError } 9001006 - If the resource re-ref too much.
 * @since 9
 */
getStringSync(resource: Resource): string;

更多关于HarmonyOS鸿蒙Next中$r("app.string.test")获取的字符串资源怎么转换成字符串?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


ContextUtil.getInstance().getAbilityContext().resourceManager.getStringValue($r(“app.string.EntryFormAbility_desc”)).then(value => {
LogUtil.getInstance().d(LogTag.TEST,${JSON.stringify(value)}) })

其中ContextUtil.getInstance().getAbilityContext()为UIAbilityContext自己在EntryAbility里去获取一下

在HarmonyOS鸿蒙Next中,$r("app.string.test")获取的是一个资源引用对象,而不是直接的字符串。要将其转换为字符串,可以使用getString方法。具体操作如下:

let stringResource = $r("app.string.test");
let stringValue = stringResource.getString();

getString方法会将资源引用对象转换为实际的字符串值。这样,stringValue就是app.string.test对应的字符串内容。

如果资源引用对象是动态的,或者需要根据不同的上下文获取不同的字符串,可以使用getString方法的参数来指定上下文或格式化参数。例如:

let stringValue = stringResource.getString(context, ...formatArgs);

其中,context是上下文对象,formatArgs是格式化参数。

在HarmonyOS鸿蒙Next中,$r("app.string.test")获取的是一个资源对象,要将其转换为字符串,可以使用getString()方法。具体代码如下:

String testString = getString($r("app.string.test").id);

其中,$r("app.string.test").id获取资源ID,getString()方法将资源ID转换为对应的字符串。

回到顶部