java - Android 混合语言文本 - 带有 RTL 和 LTR 文本的 String 上的 BidiFormatter

标签 java android locale bidirectional bidi

我有一个带有自定义 ViewListView,其中我有一个 TextView:

 <TextView
     android:id="@+id/textViewItemTitle"
     android:layout_width="0dp"
     android:layout_weight="1"
     android:layout_height="wrap_content"
     android:gravity="right|center_horizontal"
     android:text="title" />

TextView 包含希伯来文文本。

 if(!bidi.isRtl(event)){
     event = bidi.unicodeWrap(event);
 }

 holder.title.setText(String.format("%s  %s  %s", bidi.unicodeWrap(item.getStartTimeNoDate().trim()), event,
 bidi.unicodeWrap(item.getDuration().trim())));

第一个参数是时间 hh:mm:ss,第二个(事件)是希伯来语字符串,第三个与第一个类似。

问题: 有时事件字符串包含希伯来语和英语的混合文本,如 abc-אבג 然后所有文本的行为就像重力被留下(而不是就像我在 TextView 中定义的那样),我的意思是向左缩进。

如何解决?

最佳答案

当文本位于 TextView 中时,接受的答案将完成这项工作。这是一个更通用的答案,既适用于基本/快乐场景,也适用于其他更复杂的用例。

有些情况下会在 TextView 以外的地方使用混合语言文本。例如,文本可能会通过共享 Intent 传递给 Gmail 或 WhatsApp 等。在这种情况下,您必须结合使用以下类:

正如文档中引用的那样,这些是......

Utility class[es] for formatting text for display in a potentially opposite-directionality context without garbling. The directionality of the context is set at formatter creation and the directionality of the text can be either estimated or passed in when known.

因此,例如,假设您有一个包含英语和阿拉伯语组合的 String,并且您需要文本为

  • 从右到左 (RTL)。
  • 始终右对齐,即使句子以英语开头也是如此。
  • 英语和阿拉伯语单词顺序正确,没有乱码。

然后您可以使用 unicodeWrap() 方法实现此目的,如下所示:

String mixedLanguageText = ... // mixed-language text

if(BidiFormatter.getInstance().isRtlContext()){
    Locale rtlLocale = ... // RTL locale
    mixedLanguageText = BidiFormatter.getInstance(rtlLocale).unicodeWrap(mixedLanguageText, TextDirectionHeuristics.ANYRTL_LTR);
}

如果字符串中只有一个 RTL 语言字符,这会将字符串转换为 RTL 并将其左对齐,否则回退到 LTR。如果您希望字符串是 RTL,即使它完全是英语(一种 LTR 语言),那么您可以使用 TextDirectionHeuristics.RTL 而不是 TextDirectionHeuristics.ANYRTL_LTR

这是在没有 TextView 的情况下处理混合方向文本的正确方法。有趣的是,正如文档所述,

Also notice that these direction heuristics correspond to the same types of constants provided in the View class for setTextDirection(), such as TEXT_DIRECTION_RTL.

更新:

我刚找到 Bidi Java 中的类似乎做类似的事情。查一下!

更多引用:

1. Write text file mix between arabic and english .

2. Unicode Bidirectional Algorithm .

关于java - Android 混合语言文本 - 带有 RTL 和 LTR 文本的 String 上的 BidiFormatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20473657/

相关文章:

java - BIRT:数字类型(格式) hell

python - Unicode 和区域设置问题

java - 如果给定的条件为真,则做某事。如果为假,则重试

java - 如何从android中的自定义 ListView 中选择具有id的 TextView ?

java - java中不同类的两个矩阵相乘

android - 我工具栏右边的圆圈是什么

java - 以两个 ArrayLists 作为参数的方法

android - Xamarin Android : Application crashes (missing libmonosgen-2. 0.so)

php - java.lang.String 无法转换为 JSONObject

android - Android 4.1+ 语言环境更改后 Activity 闪烁