我有一个带有自定义 View
的 ListView
,其中我有一个 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 forsetTextDirection()
, such asTEXT_DIRECTION_RTL
.
更新:
我刚找到 Bidi
Java 中的类似乎做类似的事情。查一下!
更多引用:
关于java - Android 混合语言文本 - 带有 RTL 和 LTR 文本的 String 上的 BidiFormatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20473657/