【Android】解决TextView.setText提示Do not concatenate text displayed with setText. Use resource string

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25749749/article/details/81877968

挖坑背景

在实际的项目开发过程中,我们会经常用到TextView.setText()方法,而在进行某些单位设置时,比如 设置时间xxxx年xx月xx日 或者设置 体重xx公斤* 时,大家一般都会使用如下写法:

// 设置显示当前日期
TextView tvDate = (TextView) findViewById(R.id.main_tv_date);
tvDate.setText("当前日期:" + year + "年" + month + "月" + day + "日");

// 设置显示当前体重数值
TextView tvWeight = (TextView) findViewById(R.id.main_tv_weight);
tvWeight.setText("当前体重:" + weight + "公斤");

那么...如果你是在Android Studio上进行开发的话,你在使用该方式进行文本设置时就会看到以下提示:


问题分析

Ok,相信上图的问题是绝大多数的强迫症患者、完美主义者所不能容忍的,那么我们就来看看它到底想要怎么做才能够不折磨咱们!!!先分析AS给出的提示信息:

 Do not concatenate text displayed with setText. Use resource string with placeholders. [less...](#lint/SetTextI18n) (Ctrl+F1 Alt+T)
请勿使用setText方法连接显示文本.用占位符使用字符串资源(提示我们尽量使用strings.xml的字符串来显示文本)。
When calling TextView#setText
当使用TextView#setText方法时
* Never call Number#toString() to format numbers; it will not handle fraction separators and  locale-specific digits
* 不使用Number#toString()格式的数字;它不会正确地处理分数分隔符和特定于地区的数字。
 properly. Consider using String#format with proper format specifications (%d or %f)  instead.
考虑使用规范格式(%d或%f)的字符串来代替。
* Do not pass a string literal (e.g. "Hello") to display  text. Hardcoded text can not be properly translated to
不要通过字符串文字(例如:“你好”)来显示文本。硬编码的文本不能被正确地翻译成其他语言。
 other languages. Consider using Android resource strings instead.
考虑使用Android资源字符串。
* Do not build  messages by concatenating text chunks. Such messages can not be properly  translated.
不要通过连接建立消息文本块。这样的信息不能被正确的翻译。

通过以上信息,我们可以得知:

  • 不建议使用Numer.toString()的方式来进行字符串的转换,建议使用规范格式(%d或%f)的字符串来代替;
  • 不建议直接使用字符串文字来直接显示文本,建议直接使用Android字符串资源;
  • 不建议通过连接的方式显示消息文本块。

解决方法

通过上述对问题的分析解读,我们上述类似问题所引发的警告可以通过如下方式更规范化的使用TextView.setText()方法:

  • 使用String.format方法
  • 在strings.xml中进行如下声明(这里以日期设置为例)
<string name="current_time">当前日期:%1$d年%2$d月%3$d日</string>
  • 在代码中这样使用
// 设置显示当前日期
TextView tvDate = (TextView) findViewById(R.id.main_tv_date);
tvDate.setText(String.format(getResources().getString(R.string.current_time),year,month,day));

String.format常用格式说明:
%n 代表当前为第几参数,使strings.xml中的位置与format参数的位置对应;
$s代表为字符串数值;$d代表为整数数值;$f代表为浮点型数值。
如:%1$d代表第一个参数,数值类型为整数。

  • 使用Android字符串资源来替换字符串文字

猜你喜欢

转载自blog.csdn.net/qq_25749749/article/details/81877968