Android TextView:“不要将显示的文本与 setText 连接" [英] Android TextView : "Do not concatenate text displayed with setText"

查看:20
本文介绍了Android TextView:“不要将显示的文本与 setText 连接"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过以下方式使用 setText() 设置文本.

I am setting text using setText() by following way.

prodNameView.setText("" + name);

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

其中第一个是简单使用,第二个是设置文本和格式化文本.

In that First one is simple use and Second one is setting text with formatting text.

Android Studio 太有趣了,我用了 Menu Analyze ->代码清理,我得到了上面两行的建议.

Android Studio is so much interesting, I used Menu Analyze -> Code Cleanup and i got suggestion on above two lines like.

不要连接用 setText 显示的文本.使用资源字符串与占位符.少... (Ctrl+F1)

Do not concatenate text displayed with setText. Use resource string with placeholders. less... (Ctrl+F1)

当调用 TextView#setText:

  • 永远不要调用 Number#toString() 来格式化数字;它不会正确处理分数分隔符和特定于语言环境的数字.考虑使用具有正确格式规范(%d 或 %f)的 String#format反而.
  • 不要传递字符串文字(例如Hello")来显示文本.硬编码文本无法正确翻译成其他语言.考虑改用 Android 资源字符串.
  • 不要通过连接文本块来构建消息.此类消息无法正确翻译.

为此我能做些什么?任何人都可以帮助解释这是什么以及我应该怎么做?

What I can do for this? Anyone can help explain what the thing is and what should I do?

推荐答案

Resource 具有 getString 的 get 重载版本,它采用 Object 类型的 varargs:getString(int, java.lang.Object...).如果您在 strings.xml 中正确设置了字符串,并使用了正确的占位符,则可以使用此版本来检索最终字符串的格式化版本.例如.

Resource has the get overloaded version of getString which takes a varargs of type Object: getString(int, java.lang.Object...). If you setup correctly your string in strings.xml, with the correct place holders, you can use this version to retrieve the formatted version of your final String. E.g.

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

使用 getString(R.string.welcome_message, "Test", 0);

android 将返回一个带有

android will return a String with

 "Hello Test! you have 0 new messages"

关于 setText("" + name);

您的第一个示例 prodNameView.setText("" + name); 对我来说没有任何意义.TextView 能够处理空值.如果 name 为 null,则不会绘制任何文本.

Your first Example, prodNameView.setText("" + name); doesn't make any sense to me. The TextView is able to handle null values. If name is null, no text will be drawn.

这篇关于Android TextView:“不要将显示的文本与 setText 连接"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆