如何在 Android 中将格式化字符串与占位符一起使用? [英] How to use formatted strings together with placeholders in Android?
问题描述
在 Android 中可以在字符串中使用占位符,例如:
In Android it is possible to use placeholders in strings, such as:
<string name="number">My number is %1$d</string>
然后在 Java 代码中(在 Activity
的子类中):
and then in Java code (inside a subclass of Activity
):
String res = getString(R.string.number);
String formatted = String.format(res, 5);
甚至更简单:
String formatted = getString(R.string.number, 5);
Android 字符串资源中也可以使用一些 HTML 标签:
It is also possible to use some HTML tags in Android string resources:
<string name="underline"><u>Underline</u> example</string>
由于 String
本身不能保存任何格式信息,应该使用 getText(int)
而不是 getString(int)
方法:
Since the String
itself cannot hold any information about formatting, one should use getText(int)
instead of getString(int)
method:
CharSequence formatted = getText(R.string.underline);
返回的CharSequence
然后可以传递给Android小部件,例如TextView
,并且标记的短语将带有下划线.
The returned CharSequence
can be then passed to Android widgets, such as TextView
, and the marked phrase will be underlined.
然而,我找不到如何结合这两种方法,使用格式化字符串和占位符:
However, I could not find how to combine these two methodes, using formatted string together with placeholders:
<string name="underlined_number">My number is <u>%1$d</u></string>
如何在Java代码中处理上述资源以将其显示在TextView
中,将%1$d
替换为一个整数?
How to process above resource in the Java code to display it in a TextView
, substituting %1$d
with an integer?
推荐答案
最后我找到了一个可行的解决方案,并编写了我自己的方法来替换占位符,保留格式:
Finally I managed to find a working solution and wrote my own method for replacing placeholders, preserving formatting:
public static CharSequence getText(Context context, int id, Object... args) {
for(int i = 0; i < args.length; ++i)
args[i] = args[i] instanceof String? TextUtils.htmlEncode((String)args[i]) : args[i];
return Html.fromHtml(String.format(Html.toHtml(new SpannedString(context.getText(id))), args));
}
这种方法不需要在格式化的字符串或替换占位符的字符串中手动转义 HTML 标签.
This approach does not require to escape HTML tags manually neither in a string being formatted nor in strings that replace placeholders.
这篇关于如何在 Android 中将格式化字符串与占位符一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!