我之前针对 Swift 问过一个类似的问题,现在我在 Android/Java 中面临同样的问题。
Java中有没有一种方法可以在字符串中添加引号?引号应根据用户的语言设置正确本地化(请参阅https://en.wikipedia.org/wiki/Quotation_mark)。文本存储在数据库中时不带引号。我想在添加引号后在
TextView
中显示字符串。
例如:
String quote = "To be or not to be..."
// one or more lines of code that add localized quotation marks
// to the beginning and the end of the string
mMyTextView.setText(stringWithQuotes);
对于法国用户:«To be or not to be...»
对于德国用户:„To be or not to be...“
对于英语(美国)用户:“To be or not to be...”
我没有尝试过这个,但你也许可以使用Locale.getDefault。您可以为每个国家/地区创建一个具有不同报价的枚举,并在枚举中提供该枚举。那么只需找到与枚举匹配的区域设置并替换指定区域设置的引号字符即可。
我建议使用 这个 Stack Overflow 答案 在 HTML 中创建文本,该文本具有跨语言环境处理引号的必要机制。
然后您可以使用这个 Stack Overflow 答案 转换 HTML 以在 TextView 中显示。
我最终使用了以下解决方案:
为了使不同类型的引号与我的应用程序支持的区域设置保持同步,我为开始和结束标记创建了可翻译的字符串资源,例如
<string name="left_quote">\u00ab</string>
<string name="right_quote">\u00bb</string>
用于法语引号,然后将它们添加到代码中的字符串中。非常简单且易于维护。
在 Android 9 中,来自 ICU 的 LocaleData 现在已包含在 Android 中,因此您可以执行以下操作:
fun getQuotationStart(locale: Locale): String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
LocaleData.getInstance(ULocale.forLocale(locale))
.getDelimiter(LocaleData.QUOTATION_START) else "\""
fun getQuotationEnd(locale: Locale): String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
LocaleData.getInstance(ULocale.forLocale(locale))
.getDelimiter(LocaleData.QUOTATION_END) else "\""
fun String.withLocalizedQuote(locale: Locale) = "${getQuotationStart(locale)}$this${getQuotationEnd(locale)}"