假设我有这个字符串:
您的球员拥有良好的守门员技能和体面的人际交往能力
现在字符串中非粗体部分始终相同,运行时已知的是粗体部分。
那么我该怎么做:
您的球员拥有{var1}守门员技能和{var2}人际交往能力
然后在运行时用正确的值填充这些变量?
我不想像这样连接字符串:
"You player has a" + var1 + "keeper skill and a" + var2 + "people skill"
最佳答案
您需要查看 Android 字符串资源指南。有一种方法可以提供静态字符串,稍后可以使用变量对其进行格式化。
http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
你将像这样定义字符串
<resources>
<string name="welcome_messages">Hello, %1$s! You have <b>%2$d new messages</b>.</string>
</resources>
稍后在代码中您可以替换
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);
关于android - 处理 res/values 中的 Android 动态文本字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7646639/