TextView的setText注意事项

##Do not concatenate text displayed with setText 当使用下面的方法对TextView进行setText时

prodNameView.setText("" + name);  
prodOriginalPriceView.setText("" + String.format(getString(R.string.string_product_rate_with_ruppe_sign), "" + new BigDecimal(price).setScale(2, RoundingMode.UP)));

会有如下提示

Do not concatenate text displayed with setText. Use resource string with placeholders.

When calling TextView#setText:

  • Never call Number#toString() to format numbers; it will not handle fraction separators and locale-specific digits properly. Consider using String#format with proper format specifications (%d or %f) instead.
  • 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.
  • Do not build messages by concatenating text chunks. Such messages can not be properly translated.

简单来说使用TextView的setText方法时,有三点要注意的:

  • 如果有数字,使用String#format方法来格式化
  • 别硬编码,而是使用Android的String资源文件
  • 别使用+进行字符串拼接

##例子 在String资源文件中声名

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

在TextView中通过setText设置

hello.setText(getString(R.string.welcome_messages,"John",10));

##参考 stackoverflow中的问题

Android官方文档

转载于:https://my.oschina.net/neumeng/blog/541891

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值