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

查看:590
本文介绍了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非常有趣,我使用菜单 Analyze -> Code Cleanup ,我在上面两行得到了建议.

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资源字符串.
  • 不要通过串联文本块来构建消息.此类消息无法正确翻译.
  • 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.

对此我该怎么办?任何人都可以帮助解释这是什么,我该怎么办?

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

推荐答案

资源具有getString的get重载版本,其类型为Objectvarargs:

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天全站免登陆