android基础--TextView.Do not concatenate text displayed with setText. Use resource string with placeho

我们在使用TextView显示内容的过程中,经常遇到需要显示的内容只有少许参数需要改变,比如:
距离过年还有xx天xx时xx秒,当我们在更新TextView的内容时,一般是这么写的:

TextView mTextView = this.findViewById(R.id.mTextView);
mTextView.setText("距离过年还有"+mDay+"天"+mMinute+"时"+mSecond+"秒");
如果你是用Android Studio开发的话,那么它应该送你以下的警告:

Do not concatenate text displayed with setText,use resource string with placeholders
[撇脚翻译:应使用资源字符串来显示文本占位符],这里所说的就是mDay、mMinute、mSecond这些变量了。
当然对于这些警告我们其实可以不理它们,它只是告诉我们这样写不规范,但如果我们要消除这个警告,
可以使用以下的实现:
string.xml中的资源声明

<string name="delay_time">距离过年还有%1$d天%2$d时%3$d秒</string>
在代码中的使用:

mTextView.setText(String.format(getResources().getString(R.string.delay_time),mDay,mMinute,mSecond));
常用格式:
%n$s--->n表示目前是第几个参数 (比如%1$s中的1代表第一个参数),s代表字符串
%n$d--->n表示目前是第几个参数 (比如%1$d中的1代表第一个参数),d代表整数
%n$f--->n表示目前是第几个参数 (比如%1$f中的1代表第一个参数),f代表浮点数
--------------------- 
作者:BunToy 
来源:CSDN 
原文:https://blog.csdn.net/xiabing082/article/details/54092357 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/qq_38335172/article/details/86150789