版权声明:本文为博主原创文章,商业转载请联系博主获得授权,非商业转载请注明出处,否则追究其法律责任。 https://blog.csdn.net/u013642500/article/details/80167402
转载请注明出处,原文链接:https://blog.csdn.net/u013642500/article/details/80167402
【错误】
Do not concatenate text displayed with setText. Use resource string with placeholders.
【翻译】
不要在setText方法中显示地连接字符串。使用带占位符的资源字符串。
【造成原因】
在TextView对象引用setText方法时,传入的是自己连接的字符串。
【举例】
字符串资源(strings.xml):
<resources>
<string name="txtText1">text1:</string>
<string name="txtText2">text2:</string>
<string name="txtText3">text3:</string>
<string name="txtText4">text4:</string>
</resources>
Java代码:
TextView textView = new TextView(this);
private void mySetText(int i) {
textView.setText(getString(R.string.txtText1) + i);
// 此处报错:Do not concatenate text displayed with setText. Use resource string with placeholders.
}
private void mySetText(float f) {
textView.setText(getString(R.string.txtText2) + f);
// 此处报错:Do not concatenate text displayed with setText. Use resource string with placeholders.
}
private void mySetText(String s) {
textView.setText(getString(R.string.txtText3) + s);
// 此处报错:Do not concatenate text displayed with setText. Use resource string with placeholders.
}
private void mySetText(int i, float f, String s) {
textView.setText(getString(R.string.txtText4) + i + "\t" + f + "\t" + s);
// 此处报错:Do not concatenate text displayed with setText. Use resource string with placeholders.
}
【解决方法】
1、在资源文件strings.xml中修改字符串内容。
<resources>
<string name="txtText1">text1:%1$d</string>
<string name="txtText2">text2:%1$f</string>
<string name="txtText3">text3:%1$s</string>
<string name="txtText4">text4:%1$d\t%2$f\t%3$s</string>
</resources>
2、在TextView对象引用setText方法时,传入getString方法。
TextView textView = new TextView(this);
private void mySetText(int i) {
textView.setText(String.format(getString(R.string.txtText1), i));
}
private void mySetText(float f) {
textView.setText(String.format(getString(R.string.txtText2), f));
}
private void mySetText(String s) {
textView.setText(String.format(getString(R.string.txtText3), s));
}
private void mySetText(int i, float f, String s) {
textView.setText(String.format(getString(R.string.txtText4), i, f, s));
}
【解释】
利用String类的format方法,识别传入字符串格式,然后再组合,以确保程序的稳定性。
格式说明:“%1”代表第1个参数;
“%2”代表第2个参数;
“%3”代表第3个参数;
“$d”代表整型;
“$f”代表浮点型;
“$s”代表字符串。
【相关警告】
错误:Do not concatenate text displayed with setText. Use resource string with placeholders.
详见:https://blog.csdn.net/u013642500/article/details/80166941
【说明】
本文可能未必适用所有情形,本人尚属初学者,如有错误或疑问请评论提出,由衷感谢!