由于我针对的是 Android 的较新 SDK 版本,因此我收到了关于这行代码的警告:
return getString(R.string.usertab1).toUpperCase()
当我将鼠标悬停在它上面时,它会说:
Implicitly using the default locale is a common source of bugs: Use
toUpperCase(Locale)
instead.
有谁知道如何消除这个错误?为什么现在是使用这种方法的首选方式?
我知道这就是答案,使用 toUpperCase(Locale)
但在实现时遇到了麻烦。 Locale
对象从何而来?
最佳答案
您可以显式使用默认语言环境:
return getString(R.string.usertab1).toUpperCase(Locale.getDefault());
基本上,您不希望隐式允许设备使用默认值,因为这可能意味着您只是忽略了它可能是一个问题的事实。对于机器可读的内容,您可能需要指定特定的语言环境(例如 Locale.ENGLISH
),以确保始终从数据中获得所需的可重用性。为了向用户展示,明确指定默认区域设置应该没问题。
更完整的阅读:
A common mistake is to implicitly use the default locale when producing output meant to be machine-readable. This tends to work on the developer's test devices (especially because so many developers use en_US), but fails when run on a device whose user is in a more complex locale.
For example, if you're formatting integers some locales will use non-ASCII decimal digits. As another example, if you're formatting floating-point numbers some locales will use
','
as the decimal point and'.'
for digit grouping. That's correct for human-readable output, but likely to cause problems if presented to another computer (parseDouble(String)
can't parse such a number, for example). You should also be wary of thetoLowerCase()
andtoUpperCase()
overloads that don't take a Locale: in Turkey, for example, the characters'i'
and'I'
won't be converted to'I'
and'i'
. This is the correct behavior for Turkish text (such as user input), but inappropriate for, say, HTTP headers.
关于android - toUpperCaseLocale() 与 toUpperCase() - 现在针对 Android 4.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13535717/