首页 > 解决方案 > 在 RTL 字符串中间使用 LTR 文本时 TextView 中的文本方向更改

问题描述

我们的应用程序支持不同的本地人。中间有一个带有两个可替换值的字符串(带有货币符号的货币 USD$XXXXX )。但是,当语言环境是阿拉伯语时,就会出现奇怪的行为。当文本超过一行时,文本的方向会发生变化。只有第一行的文本是正确的,而其他行的格式会被某些东西覆盖!

正如您在屏幕截图中看到的那样,绿线是正确的,而红线是错误的。

在此处输入图像描述

到目前为止,我已经尝试使用:

问题是,使用双向格式后,第一个数字是正确的,而第二个数字是不正确的。

并且使用 BidiFormat 和 unicode 后,所有数字都很好,但是当文本很长并且变成多行时,只有第一行是正确的,其他行又是错误的。

对于unicode,我看了:Unicode® Standard Annex #9 UNICODE BIDIRECTIONAL ALGORITHM (如果你只对主要内容感兴趣 可以直接看这部分)

你可以看看这个 repo:Github Link

这是我用于快速参考的代码:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    setTextViewTexts(R.id.tvLtrOneLine, formatWithCurrency(), R.string.text_short_english)
    setTextViewTexts(R.id.tvLtrTwoLines, formatWithCurrency(), R.string.text_long_english)
    setTextViewTexts(R.id.tvRtlOneLine, formatWithCurrency(), R.string.text_short_arabic)
    setTextViewTexts(R.id.tvRtlOneLineBidi, bidiFormatter(formatWithCurrency()), R.string.text_short_arabic)
    setTextViewTexts(R.id.tvRtlOneLineRtlFormatter, rtlMaker(formatWithCurrency()), R.string.text_short_arabic)
    setTextViewTexts(R.id.tvRtlTwoLines, formatWithCurrency(), R.string.text_long_arabic)
    setTextViewTexts(R.id.tvRtlTwoLinesBidi, bidiFormatter(formatWithCurrency()), R.string.text_long_arabic)
    setTextViewTexts(R.id.tvRtlTwoLinesRtlFormatter, rtlMaker(formatWithCurrency()), R.string.text_long_arabic)
}

private fun setTextViewTexts(textViewId: Int, text: String, stringResource: Int) {
    findViewById<TextView>(textViewId).text = getString(stringResource, text, text)
}

private fun formatWithCurrency(): String {
    val currency = "USD$"
    val price = 200
    val priceBuilder = StringBuilder("")
    priceBuilder.append(currency)
    priceBuilder.append(getDecimalFormattedPrice(price))
    return priceBuilder.toString()
}

private fun getDecimalFormattedPrice(price: Int): String {
    return DecimalFormat("0.00").format(price)
}

private fun rtlMaker(text: String): String {
    return "\u2066" + bidiFormatter(text) + "\u2069"
}

private fun bidiFormatter(text: String): String {
    return BidiFormatter.getInstance().unicodeWrap(text)
}

它是一个android错误还是有解决方法?

要查看错误,请下载存储库并在任何设备上运行它并将设备语言更改为阿拉伯语(埃及)

编辑:我提交错误报告

标签: androidtextviewright-to-leftbidi

解决方案


您可以使用@Omid Heshmatinia, spannableString 或者 Html.fromHtml(string) 它可以为您提供更准确的输出:)


推荐阅读