前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Android】解决TextView.setText提示Do not concatenate text displayed with setText. Use resource string

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

作者头像
程思扬
发布2022-01-10 14:59:55
1.9K0
发布2022-01-10 14:59:55
举报
文章被收录于专栏:程思阳的专栏

挖坑背景

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

代码语言:javascript
复制
// 设置显示当前日期
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给出的提示信息:

代码语言:javascript
复制
 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中进行如下声明(这里以日期设置为例)
代码语言:javascript
复制
<string name="current_time">当前日期:%1$d年%2$d月%3$d日</string>
  • 在代码中这样使用
代码语言:javascript
复制
// 设置显示当前日期
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代表为浮点型数值。 如:%1d代表第一个参数,数值类型为整数。

  • 使用Android字符串资源来替换字符串文字
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/08/20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 挖坑背景
  • 问题分析
  • 解决方法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档