Android获取系统语言环境的不同方法

标签 android locale android-resources android-configchanges

因此,我发现在 Android 中有两种获取系统语言环境的方法:

Locale.getDefault()

getResources().getConfiguration().locale

基本上问题是 - 这两个的输出可以不同吗?或者它们总是相同的,我可以使用第一个,因为它不需要 Context 对象?

最佳答案

引自this page:

Be wary of the default locale

Note that there are many convenience methods that automatically use the default locale, but using them may lead to subtle bugs.

The default locale is appropriate for tasks that involve presenting data to the user. In this case, you want to use the user's date/time formats, number formats, rules for conversion to lowercase, and so on. In this case, it's safe to use the convenience methods.

The default locale is not appropriate for machine-readable output. The best choice there is usually Locale.US – this locale is guaranteed to be available on all devices, and the fact that it has no surprising special cases and is frequently used (especially for computer-computer communication) means that it tends to be the most efficient choice too.

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 the toLowerCase() and toUpperCase() 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获取系统语言环境的不同方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32451972/

相关文章:

android - 具有可检查实现的 FloatingActionButton

Lua 将字符串转换为数字 - 取决于语言环境

android - 对于 SwipeRefreshLayout 使用颜色整数,而不是颜色资源整数?

Java - 如何显示独立于货币区域设置的多种货币?

android - 如何使用 FileInputStream --Android 打开 *.cer 文件

android - 不同语言的字体资源

Android TextView - 每 20 个字符后添加一个新行

Android:Google map 不适用于 Phonegap

android - 在 Jetpack Compose 不可组合函数中获取上下文

c++ - 努力将 vector<char> 转换为 wstring